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

HashSet<T>

A HashSet is a bag that never keeps duplicates, like a sticker collection where you only keep one of each design. It is great for checking whether something is already in there.

In this page:

  1. HashSet<T>
Syntax
csharp
HashSet<type> setName = new HashSet<type>();
bool added = setName.Add(item);   // false if it already exists
setName.Contains(item);

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);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a HashSet<T> to keep insertion order or allow duplicates.
  2. Using a custom class without overriding Equals and GetHashCode, so equal objects are treated as different.
  3. Reading items by index, which a HashSet<T> does not support.
🔒

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.