03 July 2014

Difference between hashtable and dictionary

1. HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error.
2. Dictionary is faster than a Hashtable because there is no boxing and unboxing.
3. In Dictionary only public static members are thread safe, but all the members in a Hashtable are thread safe.
4. Dictionary is a generic type which means we can use it with any data type.
public void MethodHashTable()
{
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();
// ----------- Not Possible for HashTable ----------
//foreach (KeyValuePair<string, int> pair in objHashTable)
//{
// lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
//}
}

public void MethodDictionary()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
//dictionary.Add(1, -2); // Compilation Error

foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisp.Text = pair.Value + " " + pair.Key;
}
}

No comments: