C# HashSet

Beginner
7 min read
Updated: Nov 2026
3 examples
HashSet

Definition and Usage

In C#, HashSet<T> is a collection of unique items. Think of a guest list at the door: a name is either on the list or it is not, and writing the same name twice does not put it there twice. You put items in with Add(), ask about them with Contains(), and take them out with Remove().

A HashSet finds an item in about O(1) time on average, which is much faster than scanning a list. It has no indexer (you cannot write set[0]) and no fixed order. It lives in the System.Collections.Generic namespace, so add using System.Collections.Generic; at the top of your file.

The HashSet Methods index lists every method guide in this series.

Order is not guaranteed.

When you loop over a HashSet, items may come out in any order, and that order can change after you add or remove items. If you need a fixed order, copy the items to a List and sort it, or use SortedSet<T>.

C# Syntax

Common first steps:

C#
using System.Collections.Generic;

HashSet<string> names = new HashSet<string>();
bool first = names.Add("Asha");          // true: new item
bool again = names.Add("Asha");          // false: already there
bool has = names.Contains("Asha");       // true
int total = names.Count;                 // 1

// Ignore upper and lower case when comparing items:
HashSet<string> loose = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

HashSet vs List, Dictionary, and SortedSet

Pick the collection that matches what you need to do most:

TypeStoresOrder and repeatsGood for
HashSet<T>Unique itemsNo repeats, no promised orderFast "is it in there?" checks, removing duplicates, set math
List<T>Items by positionKeeps order, allows repeatsAn ordered list that grows and shrinks
Dictionary<TKey,TValue>Key and value pairsUnique keys, no promised orderFinding a value from a key
SortedSet<T>Unique itemsNo repeats, always sortedUnique items you must read in sorted order (slower, about O(log n))

Set Operations at a Glance

Say A = {1, 2, 3} and B = {3, 4, 5}. The first four methods change A in place. The rest only return true or false.

Call on AMeaningResult
A.UnionWith(B)Everything in A or BA becomes {1, 2, 3, 4, 5}
A.IntersectWith(B)Only what is in bothA becomes {3}
A.ExceptWith(B)A without anything in BA becomes {1, 2}
A.SymmetricExceptWith(B)In one set but not bothA becomes {1, 2, 4, 5}
A.Overlaps(B)Do they share any item?true (they share 3)
A.IsSubsetOf(B)Is every item of A also in B?false
A.SetEquals(B)Same items, in any order?false

C# Examples

Example 1 — Add Items and Skip Duplicates

A first program: add three numbers, try to add one of them again, and check what is inside.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        HashSet<int> numbers = new HashSet<int>();

        Console.WriteLine(numbers.Add(10));
        Console.WriteLine(numbers.Add(20));
        Console.WriteLine(numbers.Add(10));

        Console.WriteLine(numbers.Count);
        Console.WriteLine(numbers.Contains(20));
        Console.WriteLine(numbers.Contains(99));
    }
}

How It Works

  1. Type with one part. HashSet<int> means every item in the set is an int. Unlike a dictionary, there are no keys and values, only items.
  2. Add tells you. The first Add(10) and Add(20) store new items and return True. The second Add(10) finds the item already there, stores nothing, and returns False.
  3. No duplicates. Three Add calls were made, but Count is 2, because the set keeps each value once.
  4. Fast question. Contains answers yes or no without looking at every item. 20 is in the set (True) and 99 is not (False).

Example 2 — Remove Duplicates from an Array

Pass an array with repeats to the HashSet constructor, then copy the unique items to a list and sort them for printing.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] data = { 5, 3, 5, 1, 3, 3, 9 };
        HashSet<int> unique = new HashSet<int>(data);

        Console.WriteLine(data.Length);
        Console.WriteLine(unique.Count);

        List<int> sorted = new List<int>(unique);
        sorted.Sort();
        Console.WriteLine(string.Join(", ", sorted));
    }
}

How It Works

  1. Constructor does the work. new HashSet<int>(data) adds the array items one by one. Repeats are quietly ignored.
  2. Seven in, four out. The array still has 7 items, but the set holds only the distinct values 5, 3, 1, and 9, so Count is 4.
  3. Order is not promised. A HashSet does not guarantee the order of its items, so printing it directly could show any order.
  4. Sort to print. The items are copied into a List<int> and sorted, so the output is always 1, 3, 5, 9.

Example 3 — Combine Two Sets

Start with {1, 2, 3} and {3, 4, 5}. Find the shared item with Overlaps, then merge them with UnionWith.

C#
using System;
using System.Collections.Generic;

class Program {
    static string Show(HashSet<int> set) {
        List<int> items = new List<int>(set);
        items.Sort();
        return "{" + string.Join(", ", items) + "}";
    }

    static void Main() {
        HashSet<int> left = new HashSet<int> { 1, 2, 3 };
        HashSet<int> right = new HashSet<int> { 3, 4, 5 };

        Console.WriteLine(left.Overlaps(right));

        left.UnionWith(right);
        Console.WriteLine(Show(left));
        Console.WriteLine(Show(right));
    }
}

How It Works

  1. Two small sets. The collection initializer { 1, 2, 3 } fills each set when it is created. They share the number 3.
  2. Overlaps asks. left.Overlaps(right) is True because at least one item (3) is in both. It changes nothing.
  3. UnionWith changes left. It adds every item of right into left. The shared 3 is not doubled, so left becomes five items.
  4. Right stays the same. Only the set you call the method on is changed. Show sorts the items first, so the printed order is always the same.

Next: C# HashSet Methods Index

After you know what a HashSet is for, open the method index for a full tutorial on each HashSet API.

Start withWhy
Add()Put an item in the set and learn whether it was new
Contains()Check whether an item is in the set
UnionWith()Merge another collection into the set
RemoveWhere()Delete every item that matches a rule

Full list: C# HashSet Methods index (/c-sharp/hashset/method).

Frequently Asked Questions

It is a collection in System.Collections.Generic that stores unique items with no particular order. It can check whether an item exists very quickly.
A List keeps items in order by position and allows repeats, and Contains scans the list item by item. A HashSet keeps each item once, has no positions, and Contains is very fast on average.
No. Add returns false when the item is already in the set and the set does not change. Two items count as the same when Equals says so (or when the comparer you chose says so).
No. Do not rely on any order. Items may come out in the order you added them, but that is not guaranteed. Use SortedSet when you need sorted items, or copy to a List and sort it.
Open the C# HashSet Methods index. It lists Add, Remove, RemoveWhere, Clear, Contains, TryGetValue, the set operations, the set comparisons, capacity methods, CopyTo, and GetEnumerator.

Browse every HashSet method

Open the methods index for categorized guides with examples and FAQs.

HashSet Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful