11.1. Creating a Hash Code for a Data Type
Problem
You have created a class or structure that will be used as a key in a Hashtable
or Dictionary<T,U>
. You need to overload the GetHashCode
method in order to return a good distribution of hash values (the Discussion section defines a good distribution of hash values). You also need to choose the best hash-code algorithm to use in the GetHashCode
method of your object.
Solution
The following procedures implement hash-code algorithms and can be used to override the GetHashCode
method. Included in the discussion of each method are the pros and cons of using it, as well as why you would want to use one instead of another.
In addition, it is desirable, for performance reasons, to use the return value of the GetHashCode
method to determine whether the data contained within two objects is equal. Calling GetHashCode
to return a hash value of two objects and comparing their hash values can be faster than calling the default implementation of Equals
on the Object
type, which individually tests the equality of all pertinent data within two objects. In fact, some developers even opt to compare hash-code values returned from GetHashCode
within their overloaded Equals
method. Using a custom implementation of the Equals
method in this fashion is faster than the default implementation of the Object.Equals
method.
The simple hash
This hash accepts a variable number of integer values and XORs each value to obtain a hash code. This is a well-performing and ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.