C# · Hash set · container

HashSet<T>

A hash table of unique elements with expected O(1) add, membership test and removal, plus in-place set algebra.

using System.Collections.Generic;
public class HashSet<T> : ISet<T>, IReadOnlySet<T>

.NET 10

Operations

OperationTimeWorst caseChanges the collection
AddO(1)O(n)Yes
ContainsO(1)O(n)No
Remove / RemoveWhereO(1) for RemoveO(n) for RemoveWhere (visits every element)Yes
UnionWith / IntersectWith / ExceptWithO(m) for UnionWith and ExceptWith, where m is the size of other; IntersectWith O(n + m) in general—Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
The same bucket-and-entries layout as Dictionary<TKey, TValue>, without values.
Ordering
Unspecified.
Duplicates
Not stored: Add returns false for an element that is already present.
Mutability
Mutable; modifying during enumeration throws (Remove is allowed since .NET Core 3.0).
Memory and ownership
One entry per element plus buckets; grows like Dictionary, never shrinks on its own.
Equality and comparison
IEqualityComparer<T> from the constructor (e.g. StringComparer.OrdinalIgnoreCase) or EqualityComparer<T>.Default. Null is allowed as an element.

Pitfalls

  • Set operations (UnionWith, IntersectWith, ExceptWith) modify the set in place; LINQ Union/Intersect return new sequences.
  • Two sets with different comparers can disagree about membership; set operations assume compatible comparers.
  • Order is not insertion order; use SortedSet<T> when you need sorted iteration.

Alternatives

  • SortedSet<T> for ordered elements (O(log n))
  • FrozenSet<T> for read-only membership tests (.NET 8+)
  • BitArray for dense small integers

In other languages

References