Difference between Dictionary and Hashtable in C#

Below is the most discussed and major differences between Dictionary and Hashtable.

Dictionary Hash Table
Dictionary is a generic type which means we can use it with any data type. Hashtable is not a generic type.
Dictionary gives exception ‘KeyNotFoundException’if key not found. Hashtable gives null if key not found.
Namespace : System.Collections.Generic Namespace : System.Collections
Boxing and Unboxing is not required. Hence faster than hashtable. Boxing and Unboxing is required. Hence slower than dictionary.
Dictionary mydictionary= new Dictionary();
mydictionary.Add(1, “DOT NET”)
mydictionary.Add(2, “C Sharp”)
mydictionary.Add(3, “SQL Server”)
foreach(KeyValuePair entry in mydictionary)
{
MessageBox.Show(entry.Key + “:” + entry.Value);
}
Hashtable myhashtable= new Hashtable();
myhashtable.Add(1, “DOT NET”)
myhashtable.Add(2, “C Sharp”)
myhashtable.Add(3, “SQL Server”)
foreach(DictionaryEntry entry in myhashtable)
{
MessageBox.Show(entry.Key + “:” + entry.Value);
}
KeyValuePair is the enumerator used here. DictionaryEntry is the enumerator used here.
It relies on chaining algorithm It relies on rehashing
It maintains the order of data / entries. The order depends on the order in which the entries are added to it. Entries which are added last are faster to search than the ones which are added earlier. Here in Hashtable it does not maintain the order of entries.





Some more points:

  • Hash table and Dictionary both are Collection types. And you should know that both are hash-based collections, Both are using hash code for storing and finding an object.
  • GetHashCode() is a method to generate hash code. In hashtable 2 same objects have same hash code. But the vice versa is not true, means if the hash code of 2 objects is same, you cant be sure that the associated objects are equal. Because the hash function may generate same hash code for 2 unequal (different) objects.
  • In Dictionary you can store 2 same values to 2 different keys. But 2 different values cant have to same key. Following figures depicts the same expalained above.

Hash Table and Dictionary

Tip : Don’t use hash code to check for object equality, you can use ReferenceEquals or Equals method.

Take a look on internal structure of Hash Table.

Internal structure of Hash Table

Hash Table

Explaination:
In Hash table it uses the key for the hash function which generates a hash code(it is a numeric value which is used to retrieve or store an object) for the elements stored in the virtual bucket of elements. Hash function uses hash code to map the objects / data in the bucket that contains a collection of elements.