GetHashCode Function
This page was last reviewed on Jan 6, 2024.
Dot Net Perls
GetHashCode. Hashing is often done in VB.NET programs—we often use strings as keys to a Dictionary. Other types (any class) can also be hashed with GetHashCode.
With the Overrides keyword, we can implement our own GetHashCode on a class. This can be useful if the class has a unique field we want to base the hash on.
Example. Consider this example VB.NET program—it builds up a string by appending the value "x." This creates a new string each time.
And The result of GetHashCode is different each time—this means the integer returned is unique among these strings.
Module Module1 Sub Main() Dim value As String = "" ' Create some strings and print their hash codes. For i = 0 To 10 value += "x" ' Print value of GetHashCode. Console.WriteLine("GETHASHCODE: {0}", value.GetHashCode()) Next End Sub End Module
GETHASHCODE: 588487099 GETHASHCODE: 2037659917 GETHASHCODE: -2047743330 GETHASHCODE: 1240005642 GETHASHCODE: -1113563208 GETHASHCODE: 494194757 GETHASHCODE: -763422986 GETHASHCODE: -1835225738 GETHASHCODE: -876106756 GETHASHCODE: -1704566245 GETHASHCODE: 992105103
Overrides. How can we specify our own GetHashCode function? This is usually not needed, and is often not a good idea, but it can be done.
Part 1 We create a BlogEntry class, and print its custom GetHashCode result, which is 100.
Part 2 We create a BlogEntryDefault class, which has no custom GetHashCode, so the default hash code algorithm for objects is used.
Class BlogEntry Public Overrides Function GetHashCode() As Integer Return 100 End Function End Class Class BlogEntryDefault End Class Module Module1 Sub Main() ' Part 1: use class with overrides GetHashCode function. Dim blog = New BlogEntry() Console.WriteLine(blog.GetHashCode()) ' Part 2: use class without a custom GetHashCode. Dim blogDefault = New BlogEntryDefault() Console.WriteLine(blogDefault.GetHashCode()) End Sub End Module
100 58225482
Summary. It is possible to add a custom GetHashCode Function on VB.NET classes with the Overrides keyword. This can help in certain cases when objects are used as keys to Dictionaries.
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).
© 2007-2024 Sam Allen.