Difference between Hashtable and Dictionary in C#

  •  A HashTable or Dictionary is a data structure that stores key-value pairs.
  • Both implement the IDictionary interface.
  • The Dictionary generic class also implements the IDictionary generic interface.

Hashtable

  • Hashtable optimizes lookups. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. Itโ€™s an older .NET framework type. Itโ€™s slower than the generic Dictionary type.
  • 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.
  Hashtable hashtable = new Hashtable();
  hashtable.Add("Area", 1000);
  int value = (int)hashtable["Area"];
  • A Hashtable object consists of buckets that contain the elements of the collection.  A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections.
  • Each bucket is associated with a hash code, generated using a hash function and based on the key of the element.
  •  When an object is added to a Hashtable, it is stored in the bucket that is associated with the hash code that matches the object’s hash code. When a value is being searched for in the Hashtable, the hash code is generated for that value, and the bucket associated with that hash code is searched.
  • A Hash table is made up of a mapping function and an array.
  • The array contains your data, while the mapping function is used to assign numerical  values(keys) to the data.
  • This helps in categorizing the data, which speeds up search times when you search for it.
  • A hash function should assign unique keys to each bucket (data slot), but in practice a pair of keys might get hashed to the same table. This is known as a hash collision, and the design of the hash table must be able to take this probability into account.

Dictionary

  • A dictionary is used where fast lookups are critical. The Dictionary type provides fast lookups with keys to get values.
  • 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 which means we can use it with any data type.
 Dictionary<string, int> d = new Dictionary<string, int>();
   foreach (KeyValuePair<string, int> pair in d)
           {
               Console.WriteLine ("{0}, {1}",pair.Key,  pair.Value);
           }

Leave a Comment