In this article [Show more]
What is Hashtable in C#?
In C#, Hashtable is a collection class that stores key-value pairs, where each key is unique. It is part of the System.Collections namespace and uses a hash-based indexing mechanism to provide efficient data access. Although it has been largely replaced by the generic Dictionary<TKey, TValue>, Hashtable remains useful in certain scenarios.
Key Features of Hashtable
- Non-Generic: Stores all keys and values as objects, which means any data type can be stored.
- Unique Keys: Each key must be unique within the Hashtable.
- Null Keys/Values: Allows both null keys and null values.
- Thread Safety: Limited thread safety through SyncRoot.
- Hash-Based Access: Provides quick lookups based on a key's hash code.
Example: Using Hashtable
Here's an example that shows how to create, add, and retrieve data from a Hashtable:
using System;
using System.Collections;
public class HashtableExample
{
public static void Main()
{
// Create a hashtable and add key-value pairs
Hashtable phoneBook = new Hashtable
{
{ "Alice", "+1-202-555-0123" },
{ "Bob", "+1-202-555-0456" },
{ "Charlie", "+1-202-555-0789" }
};
// Add a new key-value pair
phoneBook["Diana"] = "+1-202-555-0345";
// Access values using the indexer syntax
Console.WriteLine($"Alice's phone number: {phoneBook["Alice"]}");
// Check if a key exists using ContainsKey
if (phoneBook.ContainsKey("Bob"))
{
Console.WriteLine($"Bob's phone number: {phoneBook["Bob"]}");
}
// Remove a key-value pair by key
phoneBook.Remove("Charlie");
// Iterate through all key-value pairs using a foreach loop
Console.WriteLine("\nRemaining contacts:");
foreach (DictionaryEntry entry in phoneBook)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
}
Best Practices for Using Hashtable
- Null Handling: Handle null keys and values carefully, as they may cause unexpected behavior.
- Thread Safety: Use SyncRoot or a synchronized wrapper if accessing the hashtable from multiple threads.
- Type Safety: Always cast retrieved values to the appropriate type to avoid runtime exceptions.
When to Use Hashtable
- Legacy Compatibility: When integrating with legacy code that already relies on Hashtable.
- Mixed Data Types: When storing different data types as objects.
- Null Keys/Values: When both null keys and values need to be supported.
Conclusion
Hashtable remains a useful collection for managing key-value pairs in C#, especially in scenarios that require mixed data types or legacy compatibility. By understanding its key features and best practices, you can use Hashtable effectively in your applications.