Wednesday 14 May 2014

Differences between Hashtable and Dictionary

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.
  • Only public static members are thread safe.
  • Dictionary is a generic type which means we can use it with any data type.

Example:

    Dictionary dictionary = new Dictionary();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);

    //dictionary.Add(1, -2); // Compilation Error

    foreach (KeyValuePair pair in dictionary)
    {
        lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    }
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.
  • All the members in a Hashtable are thread safe,
  • Hashtable is not a generic type,

Example:

    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

    lblDisplay1.Text = objHashTable[1].ToString();
    lblDisplay2.Text = objHashTable[2.99].ToString();
    lblDisplay3.Text = objHashTable['A'].ToString();
    lblDisplay4.Text = objHashTable["4"].ToString();