Why is Dictionary preferred over Hashtable in C#?

Nakul Chaudhary picture Nakul Chaudhary · Nov 19, 2008 · Viewed 541.6k times · Source

In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?

Answer

Michael Madsen picture Michael Madsen · Nov 19, 2008

For what it's worth, a Dictionary is (conceptually) a hash table.

If you meant "why do we use the Dictionary<TKey, TValue> class instead of the Hashtable class?", then it's an easy answer: Dictionary<TKey, TValue> is a generic type, Hashtable is not. That means you get type safety with Dictionary<TKey, TValue>, because you can't insert any random object into it, and you don't have to cast the values you take out.

Interestingly, the Dictionary<TKey, TValue> implementation in the .NET Framework is based on the Hashtable, as you can tell from this comment in its source code:

The generic Dictionary was copied from Hashtable's source

Source