In this article [Show more]
C# Hashtable vs. HashSet
In C#, both Hashtable and HashSet<T> are collections that use hashing to store and manage data efficiently. However, they serve different purposes and have distinct characteristics. This article explores the differences between Hashtable and HashSet<T>, providing practical use cases and examples to help you choose the best collection for your requirements.
Hashtable
Key Features
- Key-Value Storage: Stores key-value pairs, where each key maps to a unique value.
- Non-Generic: Keys and values are stored as object, meaning any type can be stored.
- Null Handling: Supports both null keys and values.
- Thread Safety: Limited thread safety through SyncRoot.
Example Usage
using System;
using System.Collections;
public class HashtableExample
{
public static void Main()
{
// Create a hashtable and add key-value pairs
Hashtable employees = new Hashtable
{
{ "E101", "Alice" },
{ "E102", "Bob" },
{ "E103", "Charlie" }
};
// Add a new key-value pair
employees["E104"] = "Diana";
// Retrieve a value using a key
Console.WriteLine($"Employee E101: {employees["E101"]}");
// Iterate through all key-value pairs
Console.WriteLine("\nAll Employees:");
foreach (DictionaryEntry entry in employees)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
}
}
HashSet<T>
Key Features
- Unique Elements: Stores only unique values, rejecting duplicates.
- Generic: Strongly typed, meaning all values must be of a specified type.
- Performance: Faster lookup, insertion, and deletion due to hash-based indexing.
- No Key-Value: Stores only values without a corresponding key.
Example Usage
using System;
using System.Collections.Generic;
public class HashSetExample
{
public static void Main()
{
// Create a hashset and add elements
HashSet<string> colors = new HashSet<string> { "Red", "Green", "Blue" };
// Add a new element, duplicates are ignored
colors.Add("Yellow");
bool addedAgain = colors.Add("Red"); // Returns false since it's a duplicate
// Check if a value exists
bool containsGreen = colors.Contains("Green");
// Iterate through all unique values
Console.WriteLine("\nUnique Colors:");
foreach (string color in colors)
{
Console.WriteLine(color);
}
Console.WriteLine($"Was 'Red' added again? {addedAgain}");
Console.WriteLine($"Does set contain 'Green'? {containsGreen}");
}
}
Key Differences
Structure:
- Hashtable: Stores key-value pairs.
- HashSet<T>: Stores unique values only.
Generic vs. Non-Generic:
- Hashtable: Non-generic, requires casting.
- HashSet<T>: Generic, provides type safety.
Duplicates:
- Hashtable: Allows duplicate values (but not keys).
- HashSet<T>: Disallows duplicates.
Conclusion
Hashtable and HashSet<T> serve different purposes in C# applications. Use Hashtable for key-value pairs where you need to retrieve data by key, and HashSet<T> when you only need a collection of unique values.