GetHashCode
This method implements hashing in .NET. We can override
the GetHashCode
method that is present on object for custom hashing.
Usually it is best to just leave the GetHashCode
implementations alone. Sometimes using a unique string
value within a class
may be a good choice for GetHashCode
.
We can call GetHashCode
on a string
, but this usually doesn't do much good. This program shows how when we append a char
to a string
, the hash code keeps changing.
using System; class Program { static void Main() { string value = ""; for (int i = 0; i < 10; i++) { value += "x"; // This calls the optimized hash code implementation. Console.WriteLine("GETHASHCODE: " + value.GetHashCode()); } } }GETHASHCODE: -842352680 GETHASHCODE: -838682664 GETHASHCODE: -126710822 GETHASHCODE: 1988791258 GETHASHCODE: 847333320 GETHASHCODE: 844711880 GETHASHCODE: 1653319342 GETHASHCODE: -1698453842 GETHASHCODE: -795746332 GETHASHCODE: -803610652
Suppose we have a class
that contains a unique string
value or some other unique value. We could override
GetHashCode
, and return a hash code based on that value.
override
GetHashCode
on a class
, and always return 100.using System; using System.Collections.Generic; class BlogEntry { public override int GetHashCode() { // Override the GetHashCode method that is defined on object, // which is the base class for all classes. return 100; } } class Program { static void Main() { var blog = new BlogEntry(); Console.WriteLine(blog.GetHashCode()); // The dictionary uses GetHashCode for lookup and addition. var dict = new Dictionary<BlogEntry, bool>(); dict[blog] = true; } }100
IEqualityComparer
This class
can specify how a class
should compare items and compute identity numbers for hash tables. We can customize the hash code based on specific data.
GetHashCode
is called when we use a Hashtable
or Dictionary
. All objects implement GetHashCode
, and this method can be overridden to change the hash code.