I’ve made the assumption that the (generic) Dictionary class in .NET uses the GetHashCode() method on its keys to produce hashes. I have two questions leading on from it:
-
Object has an overridable GetHashCode() method. For a user defined
reference type object, will this method produce a hash based on the
referenced data? e.g. If I have a class OneString which contains
only one String instance variable – will two separate instances of
this class with matching strings always produce the same hash code?
Or does the GetHashCode() method of OneString need to be overridden
to achieve this functionality? -
Presumably the hash function implemented in the String class is different to the hash function implemented in a different reference type (e.g. BitmapImage). Are the hash functions implemented in the most common classes publicly available?
No.
object.GetHashCode()returns a value based on that object’s identity alone.It will not return the same value for two equivalent objects; it is completely unaware of the type or meaning of the object.
Classes that represent values (such as
String) overrideGetHashCode()to return a hash based on the value represented.The algorithm used is up to the class designer;
GetHashCode()is written like any other method.However,
GetHashCode()is supposed to return equal values wheneverEquals()returns true; if your class does not do this, it is wrong.