C# Hashtable:

C# includes Hashtable collection in System.Collections namespace, which is similar to generic Dictionary collection. The Hashtable collection stores key-value pairs. It optimizes lookups by computing the hash code of each key and stores it in a different bucket internally and then matches the hash code of the specified key at the time of accessing values.

Important Propertis and Methods of Hashtable:

Property Description
Count Gets the total count of key/value pairs in the Hashtable.
IsReadOnly Gets boolean value indicating whether the Hashtable is read-only.
Item Gets or sets the value associated with the specified key.
Keys Gets an ICollection of keys in the Hashtable.
Values Gets an ICollection of values in the Hashtable.
Methods Usage
Add Adds an item with a key and value into the hashtable.
Remove Removes the item with the specified key from the hashtable.
Clear Removes all the items from the hashtable.
Contains Checks whether the hashtable contains a specific key.
ContainsKey Checks whether the hashtable contains a specific key.
ContainsValue Checks whether the hashtable contains a specific value.
GetHash Returns the hash code for the specified key.

Add key-value into Hashtable:

The Add() method adds an item with a key and value into the Hashtable. Key and value can be of any data type. Key cannot be null whereas value can be null.

Add() Signature: void Add(object key, object value);

Example: Add()

Hashtable ht = new Hashtable();

ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add(5, null);
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5);

You can also assign key and value at the time of initialization using object initializer syntax:

Example: Add()

Hashtable ht = new Hashtable()
                {
                    { 1, "One" },
                    { 2, "Two" },
                    { 3, "Three" },
                    { 4, "Four" },
                    { 5, null },
                    { "Fv", "Five" },
                    { 8.5F, 8.5 }
                };

Hashtable can include all the elements of Dictionary as shown below.

Example: Add()

Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");

Hashtable ht = new Hashtable(dict);

 
Note : Add() will throw an exception if you try to add a key that already exists in the Hashtable. So always check the key using the Contains() or ContainsKey() method before adding a key-value pair into the Hashtable.

Access Hashtable:

You can retrive the value of an existing key from the Hashtable using indexer. Please note that the hashtable indexer requires a key.

Example: Access Hashtable

Hashtable ht = new Hashtable();

ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5F);
    
string strValue1 = (string)ht[2];
string strValue2 = (string)ht["Fv"];
float fValue = (float) ht[8.5F];

Console.WriteLine(strValue1);
Console.WriteLine(strValue2);
Console.WriteLine(fValue);

Output:
Two
Five
8.5
Note : Hashtable is a non-generic collection so it can contains a key and a value of any data type. So values must be cast to an appropriate data type otherwise it will give compile-time error.

Hashtable elements are key-value pairs stored in DictionaryEntry. So you cast each element in Hashtable to DictionaryEntry. Use the foreach statement to iterate the Hashtable, as shown below:

Example: Iterate Hashtable

Hashtable ht = new Hashtable();

ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5);

foreach (DictionaryEntry item in ht)
        Console.WriteLine("key:{0}, value:{1}",item.Key, item.Value);

Output:
Key: Fv, Value: Five
Key: 8.5, Value: 8.5
Key: 4, Value: Four
Key: 3, Value: Three
Key: 2, Value: Two
Key: 1, Value: One

Hashtable has a Keys and a Values property that contain all the keys and values respectively. You can use these properties to get the keys and values.

Example: Access Hashtable using Keys & Values

Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5);

foreach (var key in ht.Keys )
        Console.WriteLine("Key:{0}, Value:{1}",key , ht[key]);

Console.WriteLine("***All Values***");
        
foreach (var value in ht.Values)
        Console.WriteLine("Value:{0}", value);

Output:
Key: Fv, Value: Five
Key: 8.5, Value: 8.5
Key: 4, Value: Four
Key: 3, Value: Three
Key: 2, Value: Two
Key: 1, Value: One
***All Values***
Value: Five
Value: 8.5
Value: Four
Value: Three
Value: Two
Value: One

Remove elements in Hashtable:

The Remove() method removes the item with the specified key from the hashtable.

Remove() Method Signature: void Remove(object key)

Example: Remove()

Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5);

ht.Remove("Fv"); // removes {"Fv", "Five"}

Check for existing elements:

Contains() and ContainsKey() check whether the specified key exists in the Hashtable collection. ContainsValue() checks whether the specified value exists in the Hashtable.

Contains(), ContainsKey() and ContainsValue() Signatures:

bool Contains(object key)

bool ContainsKey(object key)

bool ContainsValue(object value)

Example: Contains

Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");

ht.Contains(2);// returns true
ht.ContainsKey(2);// returns true
ht.Contains(5); //returns false
ht.ContainsValue("One"); // returns true

Clear():

Clear() method removes all the key-value pairs in the Hashtable.

Clear() Method Signature: void Clear()

Example: Clear()

Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5);

ht.Clear(); // removes all elements
Console.WriteLine("Total Elements: {0}", ht.Count);

Output:
Total Elements: 0

Further Reading:

Points to Remember :

  1. Hashtable stores key-value pairs of any datatype where the Key must be unique.
  2. The Hashtable key cannot be null whereas the value can be null.
  3. Hashtable retrieves an item by comparing the hashcode of keys. So it is slower in performance than Dictionary collection.
  4. Hashtable uses the default hashcode provider which is object.GetHashCode(). You can also use a custom hashcode provider.
  5. Use DictionaryEntry with foreach statement to iterate Hashtable.