VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/hashset-in-c-sharp/

⇱ HashSet in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

HashSet in C#

Last Updated : 23 Apr, 2026

A HashSet<T> is a collection of unique elements. It does not allow duplicates and does not maintain any particular order.

  • Implemented using hash table internally.
  • Provides fast lookup, addition and deletion (average O(1) time complexity).
  • Implements ISet<T>, so you can perform set operations like union, intersection, etc.

Example: The following example shows how to create a HashSet


Output
Elements in the HashSet: 
10
20
30

Steps to Create a HashSet

The HashSet class provides different ways to create a HashSet. Here we will use the HashSet() constructor to create an instance of the HashSet class that is empty and uses the default equality comparer for the set type.

Step 1: Include System.Collections.Generic namespace

using System.Collections.Generic;

Step 2: Create a HashSet using the HashSet class

HashSet<Type_of_hashset> Hashset_name = new HashSet<Type_of_hashset>();

Performing Different Operations on HashSet

1. Adding Elements

o add elements to a HashSet, use the Add() method to add or we can also store elements in your HashSet using a collection initializer.

// Using Add method
set.Add(1);
set.Add(2);

// Using Collection Initializer

HashSet<int> s = new HashSet<int>{1, 2, 3};

2. Accessing Elements

We generally use a foreach loop to iterate through the elements of a HashSet. Example:


Output
Elements of set1:
C
C++
C#
Java
Ruby
Elements of set2:
1
2
3

3. Removing Elements

We can remove elements from a HashSet using three methods:

  • Remove(T)This method is used to remove the specified element from a HashSet object.
  • RemoveWhere(Predicate<T>): This method is used to remove all elements that match the conditions defined by the specified predicate from a HashSet collection.
  • Clear(): This method is used to remove all elements from a HashSet object.

Example:


Output
Elements (Before Removal): 5
Elements (After Removal): 4

4. Set Operations

The HashSet class also provides some methods that are used to perform different operations on sets and the methods are:

  • UnionWith(IEnumerable): This method is used to modify the current HashSet object to contain all elements that are present in itself, the specified collection or both.
  • IntersectWith(IEnumerable)This method is used to modify the current HashSet object to contain only elements that are present in that object and the specified collection.
  • ExceptWith(IEnumerable): This method is used to remove all elements in the specified collection from the current HashSet object.

Example:


Output
After Union: 1, 2, 3, 5, 4
After Intersection: 3, 5
After Difference: 3

Note: HashSet does not maintain any specific order of elements, so the output order may vary.

Comment

Explore