Dictionary and Hashtable in C# are used to hold data as a collection of key-value pair.
Dictionary
- Dictionary is generic type Dictionary<TKey,TValue>
- Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types for key and value.
- There is no need of boxing/unboxing.
- When you try to access non existing key dictionary, it gives runtime error.
- Dictionary maintains an order of the stored values.
- There is no need of boxing/unboxing, so it is faster than Hashtable.
Hashtable
- Hashtable is non-generic type.
- Hashtable is a weakly typed data structure, so you can add keys and values of any object type.
- Values need to have boxing/unboxing.
- When you try to access non existing key Hashtable, it gives null values.
- Hashtable never maintains an order of the stored values.
- 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
Comments