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.
An example. 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.
So The hash computation appears to be effective—no collisions are seen when we just append a character.
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
Override. 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.
Here Just to demonstrate the syntax, we override GetHashCode on a class, and always return 100.
Warning This implementation would make hashing slow because there would be many conflicting hash codes.
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.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 6, 2024 (new example).