Why is Dictionary preferred over Hashtable in C#?


Question

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

2
1322
3/6/2019 12:56:28 AM

Accepted Answer

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

1513
12/15/2017 12:52:41 PM

Exper Answer

In .NET, the difference between Dictionary<,> and HashTable is primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though).

67
11/19/2008 9:54:50 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon