What is HashSet?

A HashSet<T> is a collection that contains unique elements only. It provides fast lookups and does not allow duplicates.

Key Features

Basic Usage

using System;
using System.Collections.Generic;

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

        // Add elements
        numbers.Add(6);  // ✅ Added
        numbers.Add(3);  // ❌ Ignored (Duplicate)

        // Remove element
        numbers.Remove(2);

        // Check existence
        bool exists = numbers.Contains(3); // true

        // Iterate
        foreach (var num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}

Set Operations

Union (Combine Two Sets)

var setA = new HashSet<int> { 1, 2, 3 };
var setB = new HashSet<int> { 3, 4, 5 };

setA.UnionWith(setB);  // setA = {1, 2, 3, 4, 5}

Intersection (Common Elements)

setA.IntersectWith(setB); // setA = {3}

Difference (Elements in A but not in B)

setA.ExceptWith(setB); // Removes elements of setB from setA

Symmetric Difference (Elements in either set, but not both)

setA.SymmetricExceptWith(setB);  // setA = {1, 2, 4, 5}

Performance Comparison

When to Use HashSet?