Search code examples
c#hashgethashcodeconsistent-hashing

How to write a good GetHashCode() implementation for a class that is compared by value?


Let's say we have such a class:

class MyClass
{
    public string SomeValue { get; set; }

    // ...
}

Now, let's say two MyClass instances are equal when their SomeValue property is equal. Thus, I overwrite the Object.Equals() and the Object.GetHashCode() methods to represent that. Object.GetHashCode() returns SomeValue.GetHashCode() But at the same time I need to follow these rules:

  1. If two instances of an object are equal, they should return the same hash code.
  2. The hash code should not change throughout the runtime.

But apparently, SomeValue can change, and the hash code we did get before may turn to be invalid.

I can only think of making the class immutable, but I'd like to know what others do in this case.

What do you do in such cases? Is having such a class represents a subtler problem in the design decisions?


Solution

  • The general contract says that if A.equals(B) is true, then their hash codes must be the same. If SomeValue changes in A in such a way that A.equals(B) is no longer true, then A.GetHashCode() can return a different value than before. Mutable objects cannot cache GetHashCode(), it must be calculated every time the method is called.

    This article has detailed guidelines for GetHashCode and mutability:

    http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/