Hashtable vs Dictionary


In this article we are going to discuss difference between Hashtable and Dictionary in C#. There are many blogs, articles are available on the internet regarding it but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Hashtable and Dictionary in C#.

In C#, both Hashtable and Dictionary are collections that store key-value pairs, but they have several differences in terms of type safety, performance, usage, and features. Here are the key differences between Hashtable and Dictionary.

Difference Between Hashtable and Dictionary in C#

S.No. Hashtable Dictionary
1 It is a non-generic collection, meaning it can store keys and values of any data type.
Hashtable vs Dictionary in C#
It is a generic collection, meaning it is type-safe. You specify the types for the keys and values when you create the dictionary, which helps prevent runtime errors.
Hashtable vs Dictionary in C#
2 Allows null values for keys and values.
Hashtable vs Dictionary in C#
Does not allow null keys, but allows null values (for reference types).
Hashtable vs Dictionary in C#
3 Use when you need to store objects of different types. Use when you need a strongly-typed collection of key-value pairs for better performance and type safety.
4 Generally slower than Dictionary because it works with object type and requires boxing and unboxing for value types. Faster due to type safety and absence of boxing/unboxing operations.
5 Example
Hashtable hashtable = new Hashtable();
hashtable.Add(1, "one");
hashtable.Add("two", 2);
Console.WriteLine(hashtable[1]);     // Output: one
Console.WriteLine(hashtable["two"]); // Output: 2
Example
Dictionary dictionary = new Dictionary();
dictionary.Add(1, "one");
dictionary.Add(2, "two");
Console.WriteLine(dictionary[1]); // Output: one
Console.WriteLine(dictionary[2]); // Output: two

Next