Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Dictionary and Hashtable [duplicate]

Tags:

c#

collections

Possible Duplicate:
Why Dictionary is preferred over hashtable in C#?

What is the difference between Dictionary and Hashtable. How to decide which one to use?

like image 505
blitzkriegz Avatar asked May 18 '09 07:05

blitzkriegz


2 Answers

Simply, Dictionary<TKey,TValue> is a generic type, allowing:

  • static typing (and compile-time verification)
  • use without boxing

If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

like image 145
Marc Gravell Avatar answered Sep 26 '22 03:09

Marc Gravell


Lets give an example that would explain the difference between hashtable and dictionary.

Here is a method that implements hashtable

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;     //} } 

The following is for dictionary

  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)     {         lblDisplay.Text = pair.Value + " " + lblDisplay.Text;     }   } 
like image 45
Pritom Nandy Avatar answered Sep 23 '22 03:09

Pritom Nandy