C# Hashtable

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:

Hash Function

It use hash sum to generate address to store data. When any request is received to retrieve data, it calculates the hash sum again using hash function and directly go to that address to retrieve the associated data.

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
  2. Value: object

We can use both members to retrieve the Key and Value of each entry. Below is the sample example:

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

Retrieve only Keys or Values

Hashtable provides a Keys and Values property to retrieve only the Keys or Values as collection.

foreach(object key in hashTable.Keys)

foreach(object value in hashTable.Values)

Update entry in C# Hashtable

For updating an entry, we need to set value again using the same key. As I said earlier, when we assign value using the same key, it overrides the data. Below is the example:

hashTable["3000"] = "Sandy";
hashTable["3000"] = "Kapil";

string name = (string)hashTable["3000"]; //Returns Kapil

Remove entry

For removing an entry, we have to use Remove method in the Hashtable. Remove methods takes the Key as parameter. It removes the particular key/value pair from the records.


Check Key/Value exists in Hashtable

There are three methods to find an entry. First two are based on searching on Keys and third one is based on using Value. All methods returns true if key/value pair exists else returns false.

  1. Contains: Search using the Key
  2. ContainsKey: Search using the Key
  3. ContainsValue: Search using the Value

Below is the examples of all three methods:

string searchByKey = "3000";
string searchByValue = "Michael";

    // key exists

    // key exists

    // value exists

Get Total number of Items

To get the total number exists, we can use the Count property which returns the integer as total number of items.

int totalRecords = hashTable.Count;

Final Words

Hashtable is optimized for faster retrieving the data. It computes the hash code from each key and use hash code to store the data. It only takes O(1) operation to retrieve any entry. Hashtable does not provide any type-safety.

Hashtable is an old data type to store data. Dictionary<> is a new data type to store key/Value pairs. Dictionary data type is of generic version. Dictionary provides type-safety and better performance as compared to Hashtable.