Difference Between Dictionary And Hashtable In C#

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#. 
  1. Dictionary<stringstring> EmployeeList = new Dictionary<stringstring>();  
  2. The following code snippet adds items to the dictionary.  
  3. EmployeeList.Add("Mahesh Chand""Programmer");  
  4. EmployeeList.Add("Praveen Kumar""Project Manager");  
  5. EmployeeList.Add("Raj Kumar""Architect");  
  6. EmployeeList.Add("Nipun Tomar""Asst. Project Manager");  
  7. EmployeeList.Add("Dinesh Beniwal""Manager");  
The following code snippet creates a HashTable in C#. 
  1. Hashtable HT = new Hashtable();    
  2. HT.Add(1,"s");    
  3. HT.Add(3, "n");    
  4. HT.Add(4, "j");    
  5. HT.Add(2, "a");    
  6. 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
  1. Dictionary is generic type Dictionary<TKey,TValue>
  2. Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types for key and value.
  3. There is no need of boxing/unboxing.
  4. When you try to access non existing key dictionary, it gives runtime error.
  5. Dictionary maintains an order of the stored values.
  6. There is no need of boxing/unboxing, so it is faster than Hashtable.
Hashtable
  1. Hashtable is non-generic type.
  2. Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
  3. Values need to have boxing/unboxing.
  4. When you try to access non existing key Hashtable, it gives null values.
  5. Hashtable never maintains an order of the stored values.
  6. Hashtable needs boxing/unboxing, so it is slower than Dictionary.
Next Recommended Reading HashTable In C# With Example