Difference between Dictionary and Hashtable in C#

Dictionary:

  • It returns error if we try to find a key which does not exist.
  • It is faster than a Hashtable because there is no boxing and unboxing.
  • Dictionary is a generic type .It is type safe.

Hashtable:

  • It returns null if we try to find a key which does not exist.
  • It is slower than dictionary because it requires boxing and unboxing.
  • Hashtable is not a generic type

If keys datatype is not defined you can use Hashtable.For Type safety you shold use Dictionary see below code lines…

Hashtable objHashTable = new Hashtable();
objHashTable.Add(1, 100); // int
objHashTable.Add(2.99, 200); // float
objHashTable.Add(‘A’, 300); // char
objHashTable.Add(“4”, 400); // string

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add(“cat”, 2);
dictionary.Add(“dog”, 1);
dictionary.Add(“llama”, 0);
// Compilation Error

Leave a comment