English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Object-Oriented Programming (OOP)

C# Hashtable (Hash Table)

HashTable is a non-generic collection that stores key-value pairs, similar to the generic Dictionary<TKey, TValue> collection. It optimizes search by calculating the hash code of each key and storing it in different buckets internally, then matching the hash code of the specified key when accessing the value.

  • HashTable Features

  • Hashtable stores key-value pairs.

  • Belongs to the System.Collection namespace.

  • Implements the IDictionary interface.

  • Keys must be unique and cannot be null.

  • Values can be null or duplicated.

  • Elements are stored as DictionaryEntry objects.

Create a hash table (HashTable)

The following example demonstrates how to create a hash table and add elements.

Hashtable numberNames = new Hashtable();
numberNames.Add(1, "One"); //Add keys using the Add() method/Value
numberNames.Add(2, "Two");
numberNames.Add(3, "Three");
//The following causes a runtime exception: The key has already been added. run-time exception: key already added.
//numberNames.Add(3, "Three"); 
foreach(DictionaryEntry de in numberNames)
    Console.WriteLine("Key: {0}, Value: {"1}"
//Using a collection-initializer syntax to create a Hashtable
var cities = new Hashtable(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
}
foreach(DictionaryEntry de in cities)
    Console.WriteLine("Key: {0}, Value: {"1}"

The Hashtable collection can include all elements of a dictionary, as shown below.

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);

Update a hash table

By passing a key to the indexer, you can retrieve the value of an existing key from the Hashtable. Since Hashtable is a non-generic collection, a value type must be typed when retrieving it.

//Using a collection-initializer syntax to create a Hashtable
var cities = new Hashtable(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
}
    
string citiesOfUK = (string) cities["UK"]; //Convert to string
string citiesOfUSA = (string) cities["USA"]; //Convert to string
Console.WriteLine(citiesOfUK);
Console.WriteLine(citiesOfUSA);
cities["UK"] = "Liverpool, Bristol"; // Update the value of UK
cities["USA"] = "Los Angeles, Boston"; //Update the value of USA
if(!cities.ContainsKey("France")){
    cities["France"] = "Paris";
}

Delete elements from the hash table

The Remove() method deletes the key-value pair that matches the specified value in the Hashtable. If the specified key is not found in the Hashtable, a KeyNotFoundException is thrown, so the ContainsKey() method is used to check for the existing key before deletion.

The Clear() method can delete all elements at once.

var cities = new Hashtable(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
}
cities.Remove("UK"); // Remove UK
//Remove UK //Throw a runtime exception: KeyNotFoundException
if(cities.ContainsKey("France")){ // Check before retrieving the key
    Remove UK
}
cities.Clear(); //Remove All Elements

Hashtable Class Hierarchy

The following figure illustrates the hierarchy of the Hashtable class.

C# Hash Table