Hash Table and Dictionary

Abstract

Hope it will give you a clear and lucid explanation of hash table and dictionary.

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 is an older .NET Framework type. It is slower than the generic Dictionary type.

Example

  1. using System.Collections;  
  2. class Program  
  3. {  
  4.     static Hashtable GetHashtable()  
  5.     {  
  6.     // Create and return new Hashtable.  
  7.     Hashtable hashtable = new Hashtable();  
  8.     hashtable.Add("Area", 1000);  
  9.     hashtable.Add("Perimeter", 55);  
  10.     hashtable.Add("Mortgage", 540);  
  11.     return hashtable;  
  12.     }  
  13.    public  static void Main()  
  14.    {  
  15.       Hashtable hashtable = GetHashtable();  
  16.       // See if the Hashtable contains this key.  
  17.       Console.WriteLine(hashtable.ContainsKey("Perimeter"));  
  18.       // Test the Contains method. It works the same way.  
  19.       Console.WriteLine(hashtable.Contains("Area"));  
  20.       // Get value of Area with indexer.  
  21.       int value = (int)hashtable["Area"];  
  22.       // Write the value of Area.  
  23.       Console.WriteLine(value);  
  24.    }  
  25. }  
Output

True
True
1000

DICTIONARY

Fast lookups are critical. The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary requires a special syntax form.
Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.

Example
  1. class DictionaryDemo  
  2. {  
  3.     static void Main()  
  4.     {  
  5.        // Example Dictionary again  
  6.        Dictionary<stringint> d = new Dictionary<stringint>()  
  7.        {  
  8.             {"Lion", 2},  {"dog", 1}};  
  9.             // Loop over pairs with foreach  
  10.             foreach (KeyValuePair<stringint> pair in d)  
  11.             {  
  12.                Console.WriteLine ("{0}, {1}",pair.Key,  pair.Value);  
  13.             }  
  14.             foreach (var pair in d)  
  15.             {  
  16.                Console.WriteLine("{0}, {1}", pair.Key, pair.Value);  
  17.             }  
  18.             Console.ReadKey();  
  19.        }      
  20.     }  
  21.  }
  22.    
Difference between Hash Table and Dictionary

Dictionary:

  • It returns error if we try to find key which is not exist.
  • It is faster than Hash Table because there is no boxing and unboxing.
  • Only public static members are thread safe.
  • Dictionary is a generic type it means we can use it with any data type.

Hash Table:

  • It returns Null if we try to find a key which is not exist.
  • It is slower than dictionary because It require boxing and unboxing.
  • All the members in Hash Table are thread safe.
  • Hash Table is not generic type.