Can a custom GetHashcode implementation cause problems with Dictionary or Hashtable's "buckets"

450 Views Asked by At

I'm considering implementing my own custom hashcode for a given object... and use this as a key for my dictionary. Since it's possible (likely) that 2 objects will have the same hashcode, what additional operators should I override, and what should that override (conceptually) look like?

   myDictionary.Add(myObj.GetHashCode(),myObj);

vs

   myDictionary.Add(myObj,myObj);

In other words, does a Dictionary use a combination of the following in order to determine uniqueness and which bucket to place an object in?

Which are more important than others?

  • HashCode
  • Equals
  • ==
  • CompareTo()

Is compareTo only needed in the SortedDictionary?

2

There are 2 best solutions below

0
On

It's not the buckets that cause the problem - it is actually finding the right object instance once you have determined the bucket using the hash code. Since all objects in a bucket share the same hash code, object equality (Equals) is used to find the right one. The rule is that if two objects are considered equal, they should produce the same hash code - but two objects producing the same hash codes might not be equal.

0
On

What is GetHashCode used for?

It is by design useful for only one thing: putting an object in a hash table. Hence the name.

GetHashCode is designed to do only one thing: balance a hash table. Do not use it for anything else. In particular:

  • It does not provide a unique key for an object; probability of collision is extremely high.
  • It is not of cryptographic strength, so do not use it as part of a digital signature or as a password equivalent
  • It does not necessarily have the error-detection properties needed for checksums.

and so on.

Eric Lippert

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