HashTable in C#

Hashtable is like a container used to store data in key/value pairs. The keys are used as like index and helps to find out the values quickly. It is a .NET Framework component. This article describes basic overview of HashTable or how to use HashTable in C#. Summary of the article:

  • What is HashTable?
  • Example of HashTable
  • When to use a HashTable?
  • HashTable vs. Dictionary

What is HashTable?
A hashtable or a hash map is a data structure that is used to implement an associative array. It is user-defined reference types. It associates keys with values. The primary operation in hash table is look like: given a key (e.g. a student’s name), find the corresponding value (e.g. that student’s ID number). It uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found. It is an older .NET Framework. It is slower than the generic Dictionary type.

Example of HashTable
Example of HashTable in C#:

Hashtable hashtable = new Hashtable();
hashtable.Add(100, "Dhaka");
hashtable.Add(200, "London");

// Display the keys.
foreach (int key in hashtable.Keys)
{
    Console.WriteLine(key);
}

// Display the values.
foreach (string value in hashtable.Values)
{
    Console.WriteLine(value);
}

Output
If we run the above C# code in a Console Application we will get the following output:
//For first loop
100
200

//For second loop
Dhaka
London

When to use a HashTable?

  • When we need to search items quickly by key
  • We can use IList or IEnumerable etc for a matching key but that will take O(n) time rather than O(1) for Hashtable or Dictionary

Hashtable vs. Dictionary
The Differences between Hashtable and Dictionary:

Hashtable:

  1. It returns null if we try to find a key which does not exist
  2. It is slower than dictionary because it requires boxing and unboxing
  3. All the members in a Hashtable are thread safe
  4. It is not a generic type that means we can’t use it with any data type

Dictionary:

  1. It returns error if we try to find a key which does not exist
  2. It is faster than a Hashtable because there is no boxing and unboxing
  3. Only public static members are thread safe
  4. It is a generic type that means we can use it with any data type

For some case we can use hashtable instead of database. Which can save time and cost. C# hashtable can play an important role in our programming.

Comments

  1. By Kamrul

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *