Using objects as key in HashTable

Written by Ingmar Verheij on March 20th, 2012. Posted in VB.Net

A HashTable can be used to store a collection of key/value pairs. The key object is used to uniquely identify the key/value pair which makes is easy to store data like a database.

The type of the key object which is added to the HashTable is variable. It can be an integer, a string, a GUID etc. Because of the nature of a GUID (a globally unique identifier) it is an ideal candidate for a key object.

If you want to use a combination of two (or more) GUIDS as a key object you can create a class object, but there is a caveat.

Example #1 – How you shouldn’t use it

Let’s take create two GUID objects, called objKey1 and objKey2, and fill them with a GUID.

Now where going to create a hashtable called objHashTable where the key/value pairs are stored.

Because we want to store two GUID’s as a key object where going to create a simple class called ValueKey.

Now let’s add a key/value pair to the hashable

The hashtable objHashTable now contains one key/value pair. We can check if the key object we’ve just added is in the hashtable:

Key found #1 : True

Okay, as expected. Now let’s create a new object key with exact the same content (objKey1 and objKey2)

Since the content of the key is exactly the same (objKey1 and objKey2 isn’t changed) you expect the key to be present in the hashtable:

Key found #1 : False

That was NOT the expected result. Although the content of the key object is equal, the hashtable can’t find the key object.


Example #2 – How you should use it

The problem in example 1 is caused by the uniqueness of the KeyValue class. If you compare the two objects with Object.Equals method you’ll notice they are not equal. If the objects are not equal, the key value in the hashtable will never match.

The solution lies in the KeyValue class, it needs an override for the Equals (and GetHashCode) method.

So let’s use the same code as in example 1 but add an override for the Equals and GetHashCode in the KeyValue class.

Key found #1 : True

Key found #2 : True

Ingmar Verheij

At the time Ingmar wrote this article he worked for PepperByte as a Senior Consultant (up to May 2014). His work consisted of designing, migrating and troubleshooting Microsoft and Citrix infrastructures. He was working with technologies like Microsoft RDS, user environment management and (performance) monitoring. Ingmar is User Group leader of the Dutch Citrix User Group (DuCUG). RES Software named Ingmar RES Software Valued Professional in 2014.

More Posts - Website

Follow Me:
TwitterLinkedInGoogle Plus

Tags: , ,

Leave a comment



%d bloggers like this: