19

When should we override the GetHashCode() method provided by 'Object' class in 'System' namespace?

4 Answers 4

14

When you override Equals, basically. When you want to provide a different idea of equality than simple reference equality.

String is a good example of this - two strings are equal (under a simple Equals call) if they represent the same sequence of characters. The hash code reflects this, such that if two strings are equal they will have the same hash code. (The reverse isn't necessarily true - two unequal strings can have the same hash code, but it's unlikely.)

(Strings are tricky in other ways, mind you - there are lots of different ideas of equality based on culture and casing, but String.Equals just looks at the UTF-16 code points which make up the string, and compares them in the simplest conceivable fashion.)

Sign up to request clarification or add additional context in comments.

4 Comments

My coworker and I were just discussing this one today. Makes much more sense now. Thanks Jon.
Let's say I have a point which has two integers to describe the coordinates. How would I return a unique hashcode which is only one integer big? The more data my structure has, the higher is the chance to get the same hashes for completely different data - would it be useless to implement this if I have 7 floats as in one of my structures (which does have equality operations)?
@PacMani: Why would you need to return a unique hash code?
@JonSkeet: Oh, I thought it's used for something nearly-unique. For what is it used then?
4

If your type should follow value semantics (comparing contents) instead of reference semantics (comparing object identity) , you should write you own override of instance object.Equals().

Comments

3

If you override Equals you must override GetHashCode as well.

Comments

1

"The GetHashCode method can be overridden by a derived type. Value types must override this method to provide a hash function that is appropriate for that type and to provide a useful distribution in a hash table. For best results, the hash code must be based on the value of an instance field or property instead of a static field or property.

Objects used as a key in a Hashtable object must also override the GetHashCode method because those objects must generate their own hash code. If an object used as a key does not provide a useful implementation of GetHashCode, you can specify a hash code provider when the Hashtable object is constructed. Prior to the .NET Framework version 2.0, the hash code provider was based on the System.Collections..::.IHashCodeProvider interface. Starting with version 2.0, the hash code provider is based on the System.Collections..::.IEqualityComparer interface."

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.