When we should override the GetHashCode() method provided by 'Object' class in 'System' namespace.
-
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.)RSolberg : My coworker and I were just discussing this one today. Makes much more sense now. Thanks Jon.tush1r : thanks to John for such easy to understand description. -
If you override
Equals
you must overrideGetHashCode
as well. -
"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
-
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().
0 comments:
Post a Comment