#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.

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.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers