← Back to C# Course | Chapter 9: Collections | Lesson 4 of 7

HashSet<T>

In this page:

  1. HashSet<T>

HashSet<T>

HashSet<T> stores unique elements with no defined order and no duplicates, backed by a hash table for fast lookups. Adding an element that already exists is silently ignored — Add returns false in that case. It's ideal for membership tests and removing duplicates from data.

Note: Use HashSet<T> instead of List<T> when you only care about "does this exist?", not order or duplicates.

Example: HashSet<T>

markup
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        HashSet<int> ids = new HashSet<int> { 1, 2, 3 };
        bool added = ids.Add(2);   // already exists
        ids.Add(4);

        Console.WriteLine(added);
        Console.WriteLine(ids.Contains(3));
        Console.WriteLine(ids.Count);
    }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.