Take the 2-minute tour ×

Can anyone give a good explanation and / or links to a good resource of how hash codes are used in storing and retrieving objects in hashtables, dictionaries etc, specifically in C# / .NET.

I'm interested to see how Equals and GetHashCode are used collectively when storing and retrieving items.

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

It depends on the collection, but for a dictionary the hash code is used to determine which bucket the object is added to, and Equals is used to find the item within the bucket, amongst other items which may have the same hash.

share|improve this answer
Could you give an example where two objects would have the same hash code (and therefore be in the same bucket), but are not considered equal with Equals? By bucket, what does this really mean? Areas of the container to group objects within? –  Michael Apr 22 '10 at 22:14
@Michael: Sure. Note that the GetHashCode() implementation is not specified and can in theory change between .NET versions, but you can try it for these two strings: "zqhrehjt" and "ogjhvzfp". I get "zqhrehjt".GetHashCode() == "ogjhvzfp".GetHashCode() the value being -1985547583 in both cases. And you are right that the objects are grouped inside the container. Ideally though each group should only contain one object. If objects end in the same bucket it is called a collision and can cause poor performance. If there are too many collisions the number of buckets is increased. –  Mark Byers Apr 22 '10 at 22:22
@Michael: Also note that two items can end up in the same bucket even if they have a different hash code because the number of buckets is always less than the number of possible hash codes. If the number of buckets is increased then they might then end up in different buckets. –  Mark Byers Apr 22 '10 at 22:26
add comment

try object.GetHashCode.

"A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection. The GetHashCode method is suitable for use in hashing algorithms and data structures such as a hash table."

share|improve this answer
add comment

Your Answer


