In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
In Dictionary, you can store key/value pairs of same type. In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value. The data retrieval is slower than Dictionary due to boxing/ unboxing.
Dictionary is a generic type and returns an error if you try to find a key which is not there. The Dictionary collection is faster than Hashtable because there is no boxing and unboxing.
A dictionary is a data structure that maps keys to values. A hash table is a data structure that maps keys to values by taking the hash value of the key (by applying some hash function to it) and mapping that to a bucket where one or more values are stored.
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With