#407 – Why You Should Override GetHashCode when Overriding Equals

Whenever you override the Equals method for a class, you should also override the GetHashCode method.

GetHashCode is a method that provides values to use as keys in a hash table.  This value, the hash, is just a number that represents the value of an object, without having to look at the entire object.  The hash code can also be thought of as a key used to look the object up in a hash table.

Objects that are equivalent should always return the same hash code.

If you don’t implement GetHashCode for your object and the object ends up stored in a Dictionary or HashTable, it’s possible that the algorithms for sorting or finding elements in these structures will not work properly.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #407 – Why You Should Override GetHashCode when Overriding Equals

  1. kharlase says:

    Not quite agree that “GetHashCode is a method that provides values to use as keys in a hash table” Hashcode is not a key. Otherwise what would have happened if two non equal objects return same hashcode: “An element with the same key already exists”? This is not happening. HashCode is used to calculate the bucket where corresponding key-value pair will be placed into. http://en.wikipedia.org/wiki/Hash_table

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: