Home
C#
GetHashCode Method (override)
Updated Jan 6, 2024
Dot Net Perls
GetHashCode. This method implements hashing in .NET. We can override the GetHashCode method that is present on object for custom hashing.
virtual
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.
override
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.
IEqualityComparer
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.
Hashtable
Dictionary
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 6, 2024 (new example).
Home
Changes
© 2007-2025 Sam Allen