Dictionary and Hashtable in C# are used to hold data as a collection of key-value pair.

Dictionary

  1. Dictionary is generic type Dictionary<TKey,TValue>
  2. Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types for key and value.
  3. There is no need of boxing/unboxing.
  4. When you try to access non existing key dictionary, it gives runtime error.
  5. Dictionary maintains an order of the stored values.
  6. There is no need of boxing/unboxing, so it is faster than Hashtable.

Hashtable

  1. Hashtable is non-generic type.
  2. Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
  3. Values need to have boxing/unboxing.
  4. When you try to access non existing key Hashtable, it gives null values.
  5. Hashtable never maintains an order of the stored values.
  6. Hashtable needs boxing/unboxing, so it is slower than Dictionary.

Hashtable

A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.The members in a Hashtable are thread safe. It returns null if we try to find a key that does not exist. Hashtable is not a generic type.The Hashtable collection is slower than dictionary because it requires boxing and unboxing.To declare a Hashtable −Hashtable ht = new Hashtable();

Dictionary

Dictionary is a collection of keys and values in C#. Dictionary is included in the System.Collection.Generics namespace. 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.

To declare a Dictionary −

IDictionary<int, string> d = new Dictionary<int, string>();

Sources:

https://www.c-sharpcorner.com/blogs/difference-between-dictionary-and-hashtable-in-c-sharp

Last modified: March 21, 2019

Author

Comments

Write a Reply or Comment