Introduction: Hashtable and Dictionary in C#
In C#, Hashtable
and Dictionary
are both used to store key-value pairs, but they have some differences in terms of usage, features, and performance. Let's delve into the details of each and provide code examples with outputs to illustrate these differences.
Hashtable in C#:
Hashtable
is a collection of key/value pairs that are organized based on the hash code of the key. It is part of the System.Collections
namespace. Here's an example of using Hashtable
:
using System;
using System.Collections;
class Program
{
static void Main()
{
// Creating a Hashtable
Hashtable hashtable = new Hashtable();
// Adding key-value pairs
hashtable.Add("Name", "John");
hashtable.Add("Age", 25);
hashtable.Add("City", "New York");
// Accessing values using keys
Console.WriteLine("Name: " + hashtable["Name"]);
Console.WriteLine("Age: " + hashtable["Age"]);
Console.WriteLine("City: " + hashtable["City"]);
}
}
Output:
Name: John
Age: 25
City: New York
Dictionary in C#:
Dictionary
is part of the System.Collections.Generic
namespace and is a generic collection of key/value pairs. It provides type safety and better performance compared to Hashtable
. Here's an example:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a Dictionary
Dictionary<string, object> dictionary = new Dictionary<string, object>();
// Adding key-value pairs
dictionary.Add("Name", "Jane");
dictionary.Add("Age", 30);
dictionary.Add("City", "Los Angeles");
// Accessing values using keys
Console.WriteLine("Name: " + dictionary["Name"]);
Console.WriteLine("Age: " + dictionary["Age"]);
Console.WriteLine("City: " + dictionary["City"]);
}
}
Output:
Name: Jane
Age: 30
City: Los Angeles
Differences between Hashtable and Dictionary
Let's summarize the differences between Hashtable
and Dictionary
in the following table:
Feature | Hashtable | Dictionary |
---|---|---|
Namespace | System.Collections |
System.Collections.Generic |
Type Safety | No | Yes |
Performance | Slower due to boxing and unboxing | Faster due to generics and no boxing/unboxing |
Null keys/values | Accepts null keys and values | Accepts null values, but not null keys |
Iterating through items | Requires casting | No casting required (strongly typed) |
Syntax | hashtable["Key"] |
dictionary["Key"] |
Obsolete | Considered obsolete (use Dictionary) | Preferred and more modern |
Conclusion:
In summary, while both Hashtable
and Dictionary
can be used to store key-value pairs, Dictionary
is generally preferred in modern C# development due to its type safety, better performance, and more convenient syntax. Hashtable
is considered obsolete, and unless you have specific compatibility requirements, it is recommended to use Dictionary
or other modern collections provided by the System.Collections.Generic
namespace.
Comments (0)