C# - Dictionary vs Hashtable
In C#, both Dictionary
and Hashtable
are used to store and manage key-value pairs, but they have some key differences in their behavior and usage. Let's explore these differences with a simple explanation:
-
Dictionary:
Dictionary
is a generic collection introduced in C# 2.0.
- It is type-safe, meaning you specify the types for both keys and values when declaring a
Dictionary
.
Dictionary
provides better performance because it is strongly typed.
- You can use it with any data type as long as you define the types during declaration.
- It does not allow duplicate keys; attempting to add a duplicate key will throw an exception.
Dictionary
is recommended for most scenarios in modern C# programming.
-
Hashtable:
Hashtable
is a non-generic collection that has been available since early versions of C#.
- It is not type-safe, as it stores objects and does not enforce data type checking.
Hashtable
is less performant compared to Dictionary
because it uses boxing and unboxing for value types.
- You can use it with any data type without type checking.
- It allows duplicate keys, and if you add a duplicate key, it will overwrite the existing value associated with that key.
Here's a complete C# source code example illustrating the differences between Dictionary
and Hashtable
::
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Using Hashtable
Hashtable hashtable = new Hashtable();
// Adding key-value pairs to the Hashtable
hashtable.Add("Name", "John");
hashtable.Add("Age", 30);
hashtable.Add("City", "New York");
// Retrieving values from the Hashtable
Console.WriteLine("Using Hashtable:");
Console.WriteLine("Name: " + hashtable["Name"]);
Console.WriteLine("Age: " + hashtable["Age"]);
Console.WriteLine("City: " + hashtable["City"]);
// Using Dictionary
Dictionary<string, object> dictionary = new Dictionary<string, object>();
// Adding key-value pairs to the Dictionary
dictionary.Add("Name", "Alice");
dictionary.Add("Age", 25);
dictionary.Add("City", "Los Angeles");
// Retrieving values from the Dictionary
Console.WriteLine("\nUsing Dictionary:");
Console.WriteLine("Name: " + dictionary["Name"]);
Console.WriteLine("Age: " + dictionary["Age"]);
Console.WriteLine("City: " + dictionary["City"]);
// Updating a value in the Dictionary
dictionary["Age"] = 28;
Console.WriteLine("\nUpdated Age in Dictionary: " + dictionary["Age"]);
// Checking if a key exists in the Dictionary
if (dictionary.ContainsKey("Country"))
{
Console.WriteLine("Country: " + dictionary["Country"]);
}
else
{
Console.WriteLine("\nKey 'Country' does not exist in the Dictionary.");
}
}
}
Output:
Using Hashtable:
Name: John
Age: 30
City: New York
Using Dictionary:
Name: Alice
Age: 25
City: Los Angeles
Updated Age in Dictionary: 28
Key 'Country' does not exist in the Dictionary.
In most scenarios, using Dictionary
is recommended due to its better performance, type safety, and modern design.