introduction to hashtable in c# .net

Hashtable is part of System.Collection namespace. You can read more about collections here. The Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key. A hash table is made up of a mapping function and an array. It uses the key to access the elements in the collection. The mapping function is used to assign numerical values (keys) to the data. This helps in categorizing the data, which speeds up search times when you search for it. Hashtable is an older .NET Framework type. It is slower than the generic Dictionary type. In hashtable we don’t declare type of the object with it signature.

Lest crate an example of hashtable.

 static void Main()
                Hashtable hashtable = new Hashtable();
                hashtable[1] = "John";
                hashtable[4] = "Mike";
                hashtable[7] = "Bob";

We can use class constructor to crate empty table, and than assign values to the selected index.

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be. DictionaryEntry  defines a dictionary key/value pair that can be set or retrieved. DictionaryEntry have two properties value and key. We can use this structure to loop through all objects in the table.

 foreach (DictionaryEntry entry in hashtable)
              Console.WriteLine("{0} : {1}", entry.Key, entry.Value);


We can use conditions to check the data status before performing an action

public virtual bool ContainsKey(object key);


Hashtables are much more efficient than most other search trees when it comes to finding data. They are used in all kinds of computer software – especially database software.

We can use method like Add() or Remove() function to manipulate data in easy to understand way.

	hashtable.Add(1, "Sandy");
	hashtable.Add(2, "Bruce");


This was just an introduction to the subject, hash table is more complex subject that involves many rules like that the hash function should assign unique keys to each data slot, but in practice a pair of keys might get hashed to the same table. This is called collision. There are two ways of dealing with it. I’ll describe both of them in next post.




Author: indiedevart

Indie Games Developer

One thought on “Hashtable”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s