C# hashtable - How to use?

C# Hashtable class is a collection class where we can store data in the key/value pair. Hashtable is not type-safe. Hashtable is not generic and both key and value are based on object type.

Hashtable is used to store unique keys data. If we try to assign value to already used key, it just overrides the previous stored data.

It is based on the Hashing algorithm which is optimized for retrieving the data fast. It only takes O(1) operation to retrieve any value based on key.

Hashing algorithm is based on hash function. A hash function is any function which maps variable size key data to a particular fixed size data.

Below is the diagram of hashing algorithm:

HashFunction.png

Below are some operations we can do on Hashtable class.

Add data

There are two ways to add data into Hashtable object:

  1. Using Add method
  2. Set key and value using Indexers
Hashtable hashTable = new Hashtable();
hashTable.Add("1000", "James");
hashTable.Add("2000", "Michael");
hashTable.Add("3000", "Sandy");

Hashtable hashTableUsingIndexers = new Hashtable();
hashTableUsingIndexers["4000"] = "George";
hashTableUsingIndexers["5000"] = "Kapil";
hashTableUsingIndexers["6000"] = "Tod";

Retrieve single entry

We can retrieve the data from Hashtable using indexers. Below is the example:

string firstName = (string)hashTable["1000"]; //Result "James"

As hashTable["1000"] returns object, we have to cast the result to string.

Retrieve all entries

Hashtable implements the IEnumerable interface. That means we can use it in the foreach loop. In the loop, it returns the DictionaryEntry object each time we enumerate. DictionaryEntry class has two members:

  1. Key: object