Information Technology Reference
In-Depth Information
cannot be modified later. Object.GetHashCode() returns this value as the
hash code for a given object.
Now examine Object.GetHashCode() in light of those three rules. If two
objects are equal, Object.GetHashCode() returns the same hash value,
unless you've overridden operator==. System.Object's version of opera-
tor==() tests object identity. GetHashCode() returns the internal object
identity field. It works. However, if you've supplied your own version of
operator==, you must also supply your own version of GetHashCode() to
ensure that the first rule is followed. See Item 6 for details on equality.
The second rule is followed: After an object is created, its hash code never
changes.
The third rule, a random distribution among all integers for all inputs,
does not hold. A numeric sequence is not a random distribution among all
integers unless you create an enormous number of objects. The hash codes
generated by Object.GetHashCode() are concentrated at the low end of
the range of integers.
This means that Object.GetHashCode() is correct but not efficient. If you
create a hashtable based on a reference type that you define, the default
behavior from System.Object is a working, but slow, hashtable. When you
create reference types that are meant to be hash keys, you should override
GetHashCode() to get a better distribution of the hash values across all
integers for your specific type.
Before covering how to write your own override of GetHashCode, this sec-
tion examines ValueType.GetHashCode() with respect to those same three
rules. System.ValueType overrides GetHashCode(), providing the default
behavior for all value types. Its version returns the hash code from the first
field defined in the type. Consider this example:
public struct MyStruct
{
private string msg;
private int id;
private DateTime epoch;
}
The hash code returned from a MyStruct object is the hash code generated
by the msg field. The following code snippet always returns true, assum-
ing msg is not null:
 
Search WWH ::




Custom Search