How to write GetHashCode() correctly

time to read 2 min | 210 words

Today I spent quite a while chasing caching bugs. The reason turned out to something like this:

public override void GetHashCode()
{
  return date.GetHashCode() & name.GetHashCode() & another.GetHashCode();
}

The issue turned out to be that in most cases, the GetHashCode() returned the same value, which completely broke caching support. (For example, assume that date is MinValue, in this case, the result of this method will always be false. Using the bitwise-and actually caused us to lose uniqueness. (The same would happen for bitwise-or, by the way.)

My usual method of operation is simply to add them together, this way I at least doesn't lose uniqueness. It is possible to get duplicates using additions, but it is usually much rarer (in the previous case, we saw about one in three duplicated).