C# Hashtable (With Examples)
C# Hashtable (With Examples)
C# - Hashtable
Hashtable Characteristics
Hashtable stores key-value pairs.
Comes under System.Collection namespace.
Implements IDictionary interface.
Keys must be unique and cannot be null.
Values can be null or duplicate.
Values can be accessed by passing associated key in the indexer e.g. myHashtable[key]
Elements are stored as DictionaryEntry objects.
Creating a Hashtable
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//numberNames.Add(3, "Three");
foreach(DictionaryEntry de in numberNames)
};
foreach(DictionaryEntry de in cities)
Try it
The Hashtable collection can include all the elements of Dictionary, as shown below.
https://www.tutorialsteacher.com/csharp/csharp-hashtable 1/4
8/27/2021 C# Hashtable (With Examples)
dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");
Try it
Update Hashtable
You can retrieve the value of an existing key from the Hashtable by passing a key in indexer.
The Hashtable is a non-generic collection, so you must type cast values while retrieving it.
};
Console.WriteLine(citiesOfUK);
Console.WriteLine(citiesOfUSA);
if(!cities.ContainsKey("France")){
cities["France"] = "Paris";
Try it
ADVERTISEMENT
https://www.tutorialsteacher.com/csharp/csharp-hashtable 2/4
8/27/2021 C# Hashtable (With Examples)
The Remove() method removes the key-value that match with the specified in the Hashtable .
It throws the KeyNotfoundException if the specified key not found in the Hashtable, so check
for an existing key using the ContainsKey() method before removing.
Use the Clear() method to remove all the elements in one shot.
};
cities.Remove("UK"); // removes UK
cities.Remove("France");
Try it
https://www.tutorialsteacher.com/csharp/csharp-hashtable 3/4
8/27/2021 C# Hashtable (With Examples)
https://www.tutorialsteacher.com/csharp/csharp-hashtable 4/4