Dictionary and Hashtable in C# are used to hold data as a collection of key-value pair. This blog talks about some differences between a dictionary and a hashtable.
The following code snippet creates a Dictionary in C#.
Dictionary<string, string> EmployeeList = new Dictionary<string, string>();
// Adding items to the dictionary
EmployeeList.Add("Mahesh Chand", "Programmer");
EmployeeList.Add("Praveen Kumar", "Project Manager");
EmployeeList.Add("Raj Kumar", "Architect");
EmployeeList.Add("Nipun Tomar", "Asst. Project Manager");
EmployeeList.Add("Dinesh Beniwal", "Manager");
The following code snippet creates a HashTable in C#.
Hashtable HT = new Hashtable();
HT.Add(1, "s");
HT.Add(3, "n");
HT.Add(4, "j");
HT.Add(2, "a");
HT.Add(5, "u");
At some point, you will need to make a decision as to which of these two objects to use. Here are some of the key differences between the two.
Dictionary
- The dictionary is generic type Dictionary<TKey, TValue>
- Dictionary class is a strong type < TKey, TValue > Hence, you must specify the data types for key and value.
- There is no need for boxing/unboxing.
- When you try to access the nonexisting key dictionary, it gives a runtime error.
- The dictionary maintains an order of the stored values.
- There is no need for boxing/unboxing, so it is faster than Hashtable.
Hashtable
- Hashtable is a non-generic type.
- Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
- Values need to have boxing/unboxing.
- When you try to access non existing key Hashtable, it gives null values.
- Hashtable never maintains an order of the stored values.
- Hashtable needs boxing/unboxing, so it is slower than Dictionary.
Next: Using Dictionary in C#and Understanding C# HashTable