Equals & GetHashCode

In this blog, I will create a sample to demonstrate why we should always override GetHashCode when we override Equals.

GetHashCode comes into play in case the object is going to be used as part of a key in hash table or dictionary. .NET uses the hash code to check if a particular key has already been used. If we just override Equals and not GetHashCode - when we do explicit Equals call, the equality behavior will be different than when we add that object as key in a dictionary.

If the object class is public, mostly, we wont be sure if this object would ever become a key in a dictionary. Therefore, its always a best practice to override GetHashCode whenever we override Equals.

When GetHashCode returns the same hash, it is considered as collision. In case of collision, Equals method is called to determine equality.

Also, when you override Equals it doesn't mean that == and != will call Equals. For that we need to do operator overloading.

Let's take a look at the code -
If we don't override GetHashCode then the object gets added to the dictionary even though Equality says that they are the same.

If we override GetHashCode, the check works and the same object doesn't get added as a key. Also, because there is a collision, Equals is called again to check the equality.