Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Dictionary preferred over Hashtable in C#?

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

like image 719
Nakul Chaudhary Avatar asked Nov 19 '08 09:11

Nakul Chaudhary


People also ask

Why do we use the dictionary class instead of the Hashtable class?

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.

Why dictionary is faster than Hashtable?

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.

What is the difference between a Hashtable and a dictionary?

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.

What is the benefit of a dictionary C#?

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.


1 Answers

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

like image 184
Michael Madsen Avatar answered Sep 29 '22 10:09

Michael Madsen