The Wayback Machine - https://web.archive.org/web/20261103135353/https://www.geeksforgeeks.org/c-sharp/hashset-in-c-sharp/

HashSet in C#

Last Updated : 22 Oct, 2026

HashSet<T> is a generic collection class available in the System.Collections.Generic namespace. It uses hashing to store unique elements and does not guarantee any particular order.

  • Prevents duplicate elements and provides average O(1) insertion, removal, and lookup.
  • Supports both value types and reference types, with customizable equality comparison.
  • Implements ISet<T> and supports set operations such as union, intersection, and difference.

Example: The following example demonstrates how to create a HashSet<int>, add elements, and verify that duplicate values are not stored.

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

class GFG {
    static void Main()
    {
        // Creating a HashSet of integers
        HashSet<int> hs = new HashSet<int>();

        // Adding elements
        hs.Add(1);
        hs.Add(2);
        hs.Add(1);

        Console.WriteLine("HashSet Size: " + hs.Count);
        Console.WriteLine("Contains 1: " + hs.Contains(1));
        Console.WriteLine("Contains 2: " + hs.Contains(2));
    }
}

Output
HashSet Size: 2
Contains 1: True
Contains 2: True

Explanation: The Add() method inserts 1 and 2 into the set. When 1 is added again, the duplicate is ignored. Therefore, the Count property returns 2.

Syntax

HashSet<T> setName = new HashSet<T>();

Here:

  • HashSet<T> represents a generic collection of unique values.
  • T specifies the type of elements stored in the set.
  • setName is the name of the HashSet object.

Hierarchy of HashSet

The HashSet<T> class implements ISet<T>, which extends ICollection<T>. It also implements IReadOnlySet<T> in modern .NET versions.

hierarchy_of_hash_set
Hierarchy of HashSet
  • IEnumerable<T>: Supports iteration through elements using foreach.
  • ICollection<T>: Extends IEnumerable<T> and provides operations such as adding, removing, and counting elements.
  • ISet<T>: Extends ICollection<T> and defines set-specific operations such as union, intersection, and difference.
  • HashSet<T>: Implements ISet<T> and provides a hash-based collection that stores unique elements.

Note: The hierarchy is simplified. HashSet<T> also implements IReadOnlyCollection<T> and, in modern .NET, IReadOnlySet<T>. Unlike Java, C# has no Set interface with the exact same name.

Constructors of HashSet

The HashSet<T> class provides constructors to create an empty set, initialize a set from a collection, specify an equality comparer, or specify both an initial capacity and an equality comparer.

1. HashSet()

Creates an empty HashSet<T> that uses the default equality comparer.

HashSet<int> numbers = new HashSet<int>();

2. HashSet(int capacity)

Creates an empty HashSet with sufficient initial capacity for the specified number of elements.

HashSet<int> set = new HashSet<int>(100);

3. HashSet(IEqualityComparer<T> comparer)

Creates an empty HashSet<T> using a custom equality comparer to determine whether two elements are equal.

HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

4. HashSet(IEnumerable<T> collection)

Creates a HashSet containing the unique elements from an existing collection. Duplicate elements are automatically removed.

List<int> numbers = new List<int> { 1, 2, 2, 3 };
HashSet<int> set = new HashSet<int>(numbers);

5. HashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)

Creates a HashSet from an existing collection using a custom equality comparer.

List<string> names = new List<string> { "Java", "JAVA", "C#" };
HashSet<string> set = new HashSet<string>( names, StringComparer.OrdinalIgnoreCase);

6. HashSet(int capacity, IEqualityComparer<T> comparer)

Creates an empty HashSet with the specified initial capacity and a custom equality comparer.

HashSet<string> set = new HashSet<string>( 100, StringComparer.OrdinalIgnoreCase);

Capacity of HashSet

Capacity refers to the amount of storage allocated internally to hold elements. HashSet<T> manages its storage automatically as elements are added.

  • The internal storage uses buckets and entries to organize values by their hash codes.
  • When the existing storage is insufficient, the collection grows automatically.
  • The EnsureCapacity() method can reserve enough capacity for a specified number of elements.
  • The TrimExcess() method can reduce excess allocated storage.
C#
using System;
using System.Collections.Generic;

class GFG {
    static void Main()
    {
        HashSet<int> hs = new HashSet<int>();

        int capacity = hs.EnsureCapacity(100);

        Console.WriteLine("Capacity is at least 100: "
                          + (capacity >= 100));

        hs.Add(10);
        hs.Add(20);

        Console.WriteLine("Element Count: " + hs.Count);
    }
}

Output
Capacity is at least 100: True
Element Count: 2

Explanation: EnsureCapacity(100) reserves storage for at least 100 elements. However, Count remains 2 because only two elements are added.

Important: Unlike Java's HashSet, C# HashSet<T> does not expose a public load-factor configuration. Its internal capacity and growth strategy are implementation details, so assumptions such as an initial capacity of 16, a load factor of 0.75, or an exact doubling rule should not be applied to C#.

Collision in HashSet

HashSet<T> uses hash codes to determine where elements are stored. A collision occurs when two unequal elements produce the same hash code. Hash collisions are handled internally using the collection's bucket-and-entry structure.

conceptual_representation_of_hash
Representation Of HashSet collision

When a collision occurs:

  1. HashSet identifies the bucket associated with the hash code.
  2. It checks existing elements using an equality comparer.
  3. If an equal element already exists, the new value is not added.
  4. Otherwise, the new element is stored in the set.

Note: Unlike modern Java HashMap, C# HashSet<T> should not be described as automatically converting collision chains into red-black trees. Its collision handling is implementation-specific.

Equality Comparison in HashSet

HashSet<T> uses EqualityComparer<T>.Default by default to determine whether two values are equal. Developers can also provide a custom IEqualityComparer<T> to control equality and hashing behavior.

Example: Case-insensitive HashSet.

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

class GFG {
    static void Main()
    {
        HashSet<string> hs = new HashSet<string>(
            StringComparer.OrdinalIgnoreCase);

        Console.WriteLine(hs.Add("Geeks"));
        Console.WriteLine(hs.Add("geeks"));

        Console.WriteLine("Count: " + hs.Count);
    }
}

Output
True
False
Count: 1

Explanation: StringComparer.OrdinalIgnoreCase treats "Geeks" and "geeks" as equal. Therefore, the second insertion fails and the set contains only one element.

For custom objects, equality and hash codes must be consistent. If two objects are equal, they must return the same hash code.

Performing Various Operations on HashSet

The HashSet<T> class provides methods for adding, removing, searching, and iterating through unique elements.

1. Adding Elements in HashSet

The Add() method inserts an element if it is not already present. It returns true for a successful insertion and false for a duplicate.

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

class Geeks {
    static void Main(){
        
        HashSet<string> hs = new HashSet<string>();

        hs.Add("Geek");
        hs.Add("For");
        hs.Add("Geeks");

        bool added = hs.Add("Geek");

        Console.WriteLine("HashSet Count: " + hs.Count);
        Console.WriteLine("Duplicate Added: " + added);
    }
}

Output
HashSet Count: 3
Duplicate Added: False

Explanation: The first three values are unique. The second insertion of "Geek" returns False, so the HashSet still contains three elements.

2. Removing Elements in HashSet

The Remove() method removes a specified element from the HashSet. It returns true if the element is successfully removed and false if it is not present.

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

class Geeks{
    
    static void Main(){
        
        HashSet<string> hs = new HashSet<string>();

        hs.Add("Geek");
        hs.Add("For");
        hs.Add("Geeks");
        hs.Add("A");
        hs.Add("B");
        hs.Add("Z");

        Console.WriteLine("Initial Count: " + hs.Count);

        // Removing element B
        hs.Remove("B");

        Console.WriteLine("Count after removal: "
                          + hs.Count);

        // Checking whether B still exists
        Console.WriteLine("B exists: " + hs.Contains("B"));
    }
}

Output
Initial Count: 6
Count after removal: 5
B exists: False

Explanation: The Remove("B") method removes "B" from the HashSet, reducing its count from 6 to 5. The Contains("B") method returns False because the element no longer exists.

3. Iterating Through HashSet

Elements in a HashSet can be traversed using a foreach loop or the GetEnumerator() method. Since HashSet does not guarantee any particular order, the iteration order may vary.

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

class Geeks{
    static void Main(){
        
        HashSet<string> hs = new HashSet<string>();

        hs.Add("A");
        hs.Add("B");
        hs.Add("Geeks");
        hs.Add("For");
        hs.Add("Z");

        // Using GetEnumerator()
        Console.WriteLine("Using Enumerator:");

        var iterator = hs.GetEnumerator();

        while (iterator.MoveNext()) {
            Console.WriteLine(iterator.Current);
        }

        // Using foreach loop
        Console.WriteLine("Using foreach:");

        foreach(string element in hs)
        {
            Console.WriteLine(element);
        }
    }
}

Output
Using Enumerator:
A
B
Geeks
For
Z
Using foreach:
A
B
Geeks
For
Z

Explanation: GetEnumerator() traverses elements using MoveNext() and Current, while the foreach loop provides a simpler way to iterate over the collection. Both methods visit the stored elements without guaranteeing their order.

4. Searching Elements in HashSet

The Contains() method checks whether a specified element exists in the HashSet. It provides average O(1) lookup performance.

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

class Geeks{
    
    static void Main(){
        
        HashSet<int> hs = new HashSet<int>();

        hs.Add(10);
        hs.Add(20);
        hs.Add(30);

        Console.WriteLine(hs.Contains(20));
        Console.WriteLine(hs.Contains(40));
    }
}

Output
True
False

Explanation: Contains(20) returns True because the value exists in the HashSet, while Contains(40) returns False because it is absent.

Set Operations in HashSet

C# provides built-in methods for performing mathematical set operations.

Operation

Method

Description

Union

UnionWith()

Combines unique elements from two collections.

Intersection

IntersectWith()

Retains elements common to both collections.

Difference

ExceptWith()

Removes elements found in another collection.

Symmetric Difference

SymmetricExceptWith()

Retains elements present in exactly one collection.

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

class Geeks {
    static void Main()
    {
        HashSet<int> a = new HashSet<int>{ 1, 2, 3 };
        HashSet<int> b = new HashSet<int>{ 3, 4, 5 };

        a.UnionWith(b);

        // Sorting only for predictable output
        Console.WriteLine(
            string.Join(", ", new SortedSet<int>(a)));
    }
}

Output
1, 2, 3, 4, 5

Explanation: The UnionWith() method adds elements from set b to set a while avoiding duplicates. The SortedSet<int> is used only to display the result in sorted order.

Properties of HashSet

The HashSet<T> class provides two main properties to access information about the set.

PropertyDescription
ComparerGets the IEqualityComparer<T> object used to determine equality for the elements in the set.
CountGets the number of elements contained in the set.

Methods of HashSet

The HashSet<T> class provides methods for adding, removing, searching, and performing set operations on elements.

MethodsDescription
Add(T)Adds the specified element to the HashSet<T>.
Clear()Removes all elements from the HashSet<T>.
Contains(T)Determines whether the HashSet<T> contains the specified element.
CopyTo()Copies the elements of the HashSet<T> to an array.
CreateSetComparer()Returns an equality comparer that can be used to compare HashSet<T> objects.
ExceptWith(IEnumerable<T>)Removes all elements in the specified collection from the current HashSet<T>.
IntersectWith(IEnumerable<T>)Modifies the current HashSet<T> to contain only elements present in both collections.
IsProperSubsetOf(IEnumerable<T>)Determines whether the current HashSet<T> is a proper subset of the specified collection.
IsProperSupersetOf(IEnumerable<T>)Determines whether the current HashSet<T> is a proper superset of the specified collection.
IsSubsetOf(IEnumerable<T>)Determines whether the current HashSet<T> is a subset of the specified collection.
IsSupersetOf(IEnumerable<T>)Determines whether the current HashSet<T> is a superset of the specified collection.
Overlaps(IEnumerable<T>)Determines whether the current HashSet<T> and the specified collection share any elements.
Remove(T)Removes the specified element from the HashSet<T>.
RemoveWhere(Predicate<T>)Removes all elements that match the conditions defined by the specified predicate.
SetEquals(IEnumerable<T>)Determines whether the current HashSet<T> and the specified collection contain the same elements.
SymmetricExceptWith(IEnumerable<T>)Modifies the current HashSet<T> to contain only elements present in either collection, but not both.
TrimExcess()Sets the capacity of the HashSet<T> to the number of elements it contains, rounded to an implementation-specific value.
TryGetValue(T, out T)Searches the set for a given value and returns the equal value found, if any.
UnionWith(IEnumerable<T>)Modifies the current HashSet<T> to contain all elements present in either the current set or the specified collection.
Comment

Explore