C# - Hashtable vs HashSet
In C#, Hashtable and HashSet are both data structures used to store collections of elements, but they have some key differences in how they work and what they are best suited for.
- A
Hashtable
is a collection that stores key-value pairs.
- It is part of the
System.Collections
namespace.
- Keys must be unique within the
Hashtable
, but values can be duplicate.
Hashtable
is based on a hash table data structure, which provides efficient lookup and retrieval of values based on their keys.
- Elements in a
Hashtable
are not stored in any specific order.
- It is not type-safe, meaning you can store any type of object as a key or value.
Hashtable:
Here's a simple C# code example using Hashtable
:
using System;
using System.Collections;
class Program
{
static void Main()
{
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 by key
Console.WriteLine("Name: " + hashtable["name"]);
Console.WriteLine("Age: " + hashtable["age"]);
Console.WriteLine("City: " + hashtable["city"]);
}
}
HashSet:
- A
HashSet
is a collection that stores a set of unique elements.
- It is part of the
System.Collections.Generic
namespace and is type-safe, meaning it can store elements of a specific type.
- Elements in a
HashSet
are stored in an unordered manner, and there is no concept of keys or values.
- It is designed for fast membership tests, i.e., checking if an element exists in the set.
- It does not allow duplicate elements.
Here's a simple C# code example using HashSet:
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> hashSet = new HashSet<string>();
// Adding elements to the HashSet
hashSet.Add("apple");
hashSet.Add("banana");
hashSet.Add("cherry");
// Attempting to add a duplicate element
hashSet.Add("apple");
// Iterating over the elements in the HashSet
Console.WriteLine("Elements in HashSet:");
foreach (string fruit in hashSet)
{
Console.WriteLine(fruit);
}
}
}
Hashtable
is used for key-value pairs with non-unique keys and offers fast key-based retrieval, while HashSet
is used for storing unique elements without any key-value association and is optimized for membership checks. The choice between them depends on your specific requirements for data storage and retrieval.
When to Use Which:
-
If you need to associate values with keys and perform lookups based on those keys, and you need synchronization support in a multi-threaded environment, then
Hashtable
might be more suitable.
-
If you need to store a collection of distinct elements and perform set-based operations (e.g., adding, removing, checking for containment), then
HashSet
is the appropriate choice.
When using newer versions of .NET (like .NET Framework 3.5 and newer, .NET Core, .NET 5, and others), and when you need to handle separate items, it's better and more efficient to use HashSet
.