In C#, Hashtables and Dictionaries are two commonly used collection type for storing and retrieving key-value pairs.
The following example demonstrates creating a Hashtable and adding elements.
Example: Create and Add Elements
Hashtable numberNames = new Hashtable();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(DictionaryEntry de in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", de.Key, de.Value);
A Dictionary
can be created by passing the type of keys and values it can store.
Example: Create Dictionary and Add Elements
IDictionary<int, string> numberNames = new Dictionary<int, string>();
numberNames.Add(1,"One"); //adding a key/value using the Add() method
numberNames.Add(2,"Two");
numberNames.Add(3,"Three");
//The following throws run-time exception: key already added.
//numberNames.Add(3, "Three");
foreach(KeyValuePair<int, string> kvp in numberNames)
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
Hashtable vs Dictionary
The following table lists the differences between Hashtable and Dictionary in C#.
Hashtable | Dictionary |
---|---|
Hashtable is included in the System.Collections namespace. | Dictionary is included in the System.Collections.Generic namespace. |
Hashtable is a loosely typed (non-generic) collection, this means it stores key-value pairs of any data types. | Dictionary is a generic collection. So it can store key-value pairs of specific data types. |
Hashtable is thread safe. | Only public static members are thread safe in Dictionary. |
Hashtable returns null if we try to find a key which does not exist. | Dictionary throws an exception if we try to find a key which does not exist. |
Data retrieval is slower than the dictionary collection because of boxing-unboxing. | Data retrieval is faster than Hashtable because it is a type safe so no need of boxing-unboxing. |
It is recommended to use the Dictionary than the Hashtable collection in C#.
Visit Hashtable or Dictionary in the C# tutorials section for more information.
Related Articles