5

What is the difference between Dictionary and Hashtable. How can i come to conclusion on which to use?Can anyone please help me?

Riya
  • 529
  • 4
  • 10
  • 18
  • 3
    http://stackoverflow.com/questions/301371/why-dictionary-is-preferred-over-hashtable-in-c – Douglas Mar 03 '11 at 09:42
  • See similar question below: http://stackoverflow.com/questions/1089132/net-hashtable-vs-dictionary-can-the-dictionary-be-as-fast – Matt F Mar 03 '11 at 09:43

3 Answers3

6

The Dictionary class differs from the Hashtable class in more ways than one. In addition to being strongly-typed, the Dictionary also employs a different collision resolution strategy than the Hashtable class, using a technique referred to as chaining.

You can read this article: http://msdn.microsoft.com/en-us/library/ms379571(v=vs.80).aspx#datastructures20_2_topic6

It's really useful.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
Michael M.
  • 6,561
  • 1
  • 16
  • 18
1

Hashtable is obsolete. Always use Dictionary.

Dan Byström
  • 9,067
  • 5
  • 38
  • 68
1

I am newbie in hashtables too, but...

Dictionary is a basic table with two columns (Key and Value, both has certain types) and lots of rows you add later. You will see that in dictionary you give a key and dictionary gives you value you added previously by the absolutely same key.

In hashtable things are slightly different. You have table with two columns again (Key and Value, both are of "object" type). The keys might be not unique. Now you virtualy have two tables: one with two columns: Key and Hash, and other one with again two columns Hash and Value. Hash is some integer value got from Key. It turns out that while Keys might be unique, Hashes may be not. [Yet I'm not sure about this... so I said "virtualy"...]

Now example:

Hashtable ht = new Hashtable();
// Key of type Int32
ht[16] = "That is Int32";
// Key of type String
ht["Blah"] = 15;
// Key of type Boolean
ht[false] = "That is boolean";
// Key of type String
ht["Hohoho"] = false;

And later you can access any value stored in Hashtable just using keys (if there are no such key it returns null):

Console.WriteLine("ht[{0}] = {1};", 16, ht[16] ?? "null");
Console.WriteLine("ht[{0}] = {1};", "Test", ht["Test"] ?? "null"); // doesnt exist eh...
Console.WriteLine("ht[{0}] = {1};", false, ht[false] ?? "null");
Console.WriteLine("ht[{0}] = {1};", "Hohoho", ht["Hohoho"] ?? "null");

To sumarize:

Dictionary is this:

[ Key ][ Value ]
   A      1.5
   B      1.6
   C      -8
     ....

And Hashtable probabily is this:

[ Key ][ Hash ]
   A      1
   B      2
   C     -99
      ...

[ Hash ][ Value ]
   -99      -8
    1       1.6
    2       1.5
      ....

I hope this is anything helpful. Anyone who could explain it better, do not hesitate to do so.

Thank you and good luck.

ernestasju
  • 1,319
  • 1
  • 11
  • 14