Home
VB.NET
GetHashCode Function
Updated 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
Object
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.
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).
Home
Changes
© 2007-2025 Sam Allen