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:
Syntax
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>
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Expecting a
HashSet<T>to keep insertion order or allow duplicates. - Using a custom class without overriding
EqualsandGetHashCode, so equal objects are treated as different. - 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: