Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can go wrong if one fails to override GetHashCode() when overriding Equals()? [duplicate]

Tags:

c#

.net

Possible Duplicate:
Why is it important to override GetHashCode when Equals method is overridden?

In C#, what specifically can go wrong if one fails to override GetHashCode() when overriding Equals()?

like image 261
jon37 Avatar asked Mar 19 '09 00:03

jon37


2 Answers

The most visible way is for mapping structures.

Any class which does this will have unpredictable behavior when used as the Key for a Dictionary or HashTable. The reason being is that the implementation uses both GetHashCode and Equals to properly find a value in the table. The short version of the algorithm is the following

  1. Take the modulus of the HashCode by the number of buckets and that's the bucket index
  2. Call .Equals() for the specified Key and every Key in the particular bucket.
  3. If there is a match that is the value, no match = no value.

Failing to keep GetHashCode and Equals in sync will completely break this algorithm (and numerous others).

like image 173
JaredPar Avatar answered Oct 03 '22 15:10

JaredPar


Think of a hash / dictionary structure as a collection of numbered buckets. If you always put things in the bucket corresponding to their GetHashCode(), then you only have to search one bucket (using Equals()) to see if something is there. This works, provided you're looking in the right bucket.

So the rule is: if Equals() says two objects are Equal(), they must have the same GetHashCode().

like image 38
MarkusQ Avatar answered Oct 03 '22 15:10

MarkusQ