Back to results for “Set”
C# › Collections

What does HashSet<T> provide and when do you use it?

Intermediate

Answer

A set of unique elements with fast Contains/Add and set operations. Adding a duplicate is a no-op.
var seen = new HashSet<int>();
if (!seen.Add(id)) Console.WriteLine("duplicate");
Real-world example De-duplicating ids or checking membership in a loop without O(n) scans.