Hashtable or Dictionary ?

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs.

Dictionary is generic type, hash table is not a generic type.

The Hashtable is a weakly typed data structure, so you can add keys and values of any Object Type to the Hashtable. The Dictionary class is a strongly types < T Key, T Value > and you must specify the data types for both the key and value.

Hashtable numbers = new Hashtable();
Dictionary<int, string> dictionary = new Dictionary<int, string >();

While perform operations Dictionary is faster because there is no boxing/unboxing (valuetypes don’t need boxing) while in Hashtable boxing/unboxing (valuetypes need boxing) will happened and which may have memory consumption as well as performance penalties.

When we add the multiple entries in Dictionary, the order in which the entries are added is maintained. When we retrieve the items from Dictionary we will get the records in the same order we have inserted them. Whereas we add same records in Hashtable the order is not maintained.

Hashtable is thread safe for supports multiple reader threads and a single writer thread. That is the Hashtable allows ONE writer together with multiple readers without locking. In the case of Dictionary there is no thread safety, if you need thread safety you must implement your own synchronization.

When you try to get the value of key which does not exists in the collection, the dictionary throws an exception of ‘KeyNotFoundException’ while hashtable returns null value.

When using large collection of key value pairs hashtable would be considered more efficient than dictionary.

Hope this will help !!!

Jay Ganesh


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s