![]() |
VOOZH | about |
In C# both Hashtable and Dictionary are used to store key-value pairs. Understanding the difference between Hashtable and Dictionary plays a very important role in choosing the right data structure for our C# applications. The main difference between Hashtable and Dictionary is:
Note: Dictionary<TKey, TValue> is the preferred choice for most C# codes today because it’s more reliable and easier to work with.
Features | Hashtable | Dictionary |
|---|---|---|
Generic/Non-Generic | Hashtable is Non-generic. | Dictionary is generic. |
Namespace | It is defined under System.Collections | It is defined under System.Collections.Generics |
Type Safety | It does not enforce type safety. | It enforces type safety. |
Boxing/Unboxing | It is slower because boxing/unboxing of data. | It is faster because there is no boxing/unboxing. |
Accessing Missing Keys | It returns null for missing keys. | It returns KeyNotFoundException for missing keys. |
Thread-Safety | It is thread-safe | It is not thread-safe |
Performance | It is slower due to boxing/unboxing. | It is faster due to generics and no boxing/unboxing. |
A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. Or in other words, a Hashtable is used to create a collection which uses a hash table for storage. It is the non-generic type of collection which is defined in System.Collections namespace. In Hashtable, key objects must be immutable as long as they are used as keys in the Hashtable
Example: This example demonstrates how to create a Hashtable in C#, add key-value pairs, and print each key-value pair using a foreach loop.
Key: 3 and Value: GeeksforGeeks Key: 2 and Value: to Key: 1 and Value: Welcome
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. Dictionary is defined under System.Collection.Generics namespace. It is dynamic in nature means the size of the dictionary is growing according to the need
Example: This example demonstrates how to create a Dictionary in C#, add key-value pairs, and then print each key-value pair using a foreach loop.
Key: 1 and Value: C Key: 2 and Value: C++ Key: 3 and Value: C#