Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

The HashSet<T> class

Reference for C# HashSet<T>: adding unique items, fast Contains, union, intersection, difference, subset tests, custom comparers and ordering caveats.

HashSet<T> is an unordered collection of unique values. Adding a value that is already present does nothing and reports false. Checking whether a value is in the set is O(1) on average, which is far faster than List<T>.Contains on large data.

It also implements the mathematical set operations: union, intersection, difference, and tests such as subset and overlap. Equality is decided by GetHashCode() and Equals() or by a comparer you supply.

C#
var seen = new HashSet<string>();
bool isNew = seen.Add("apple");    // true
bool again = seen.Add("apple");    // false

Try it

C# Uniqueness and membership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Set operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class HashSet<T> : ISet<T>, IReadOnlySet<T>
{
    public HashSet();
    public HashSet(IEqualityComparer<T>? comparer);
    public HashSet(IEnumerable<T> collection);
    public HashSet(int capacity);

    public bool Add(T item);
    public bool Remove(T item);
    public bool Contains(T item);
    public int RemoveWhere(Predicate<T> match);

    public void UnionWith(IEnumerable<T> other);
    public void IntersectWith(IEnumerable<T> other);
    public void ExceptWith(IEnumerable<T> other);
    public void SymmetricExceptWith(IEnumerable<T> other);

    public bool IsSubsetOf(IEnumerable<T> other);
    public bool IsSupersetOf(IEnumerable<T> other);
    public bool Overlaps(IEnumerable<T> other);
    public bool SetEquals(IEnumerable<T> other);
}
Name Description
item The element to add, remove or find. null is allowed for reference types.
other Another sequence to combine with or compare to.
comparer Defines when two items are the same.
match A predicate for RemoveWhere.

Returns: Add returns true if the item was new. Remove returns true if it was present. The Is..., Overlaps and SetEquals methods return bool. The ...With methods change the set in place and return nothing.

Errors: ArgumentNullException when other or match is null. Modifying the set while enumerating it with foreach throws InvalidOperationException (RemoveWhere is the safe way to remove many).

Usage notes

  • No order, no index. A HashSet<T> has no indexer and its enumeration order is unspecified. Sort a copy (set.Order()) before printing or comparing.
  • The set operations mutate the receiver. Copy first (new HashSet<int>(a)) if you must keep the original, or use LINQ Union, Intersect and Except for new sequences.
  • Pass another HashSet with the same comparer to the operations for the fastest path; otherwise the method may have to build a temporary set.
  • Do not mutate items after adding them. An item whose hash code changes can no longer be found.
  • Membership tests are the main reason to use it. Converting a list to a set before many Contains calls turns O(nยทm) into O(n+m).
  • TryGetValue(equalValue, out actual) retrieves the stored instance equal to a probe value, useful for interning.
  • Need order? Use SortedSet<T>. Need thread safety? Guard it with a lock or use ConcurrentDictionary<T, byte>; there is no concurrent set type.
  • IReadOnlySet<T> (.NET 5+) is the interface to expose when callers should only query.