Advertisement
Intermediate C#, Collections

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

Short answer

A set of unique elements with fast Contains/Add and set operations. Adding a duplicate is a no-op.

Save C# mock interview
Advertisement
AModel 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.