Home
Map
GetHashCode Method (override)Implement the GetHashCode method with the override keyword. Test return values of GetHashCode.
C#
This page was last reviewed on Jan 6, 2024.
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 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).
Home
Changes
© 2007-2024 Sam Allen.