C# Interview Question #125

What is a HashSet<T>, and when should it be used?

Advanced LINQ, Expressions & Collections Senior Advanced

Quick Interview Answer

HashSet<T> is a generic collection that stores unique values and provides efficient membership checks.

Detailed Explanation

HashSet<T> is a generic collection that stores unique values and provides efficient membership checks.

It does not allow duplicate elements according to its equality comparer. It supports set operations such as UnionWith, IntersectWith, ExceptWith, and IsSubsetOf.

HashSet<T> is useful when uniqueness and fast Contains checks are more important than indexed access. Correct equality and GetHashCode implementations are important for custom element types.

Code Example

var tags = new HashSet<string>(
    StringComparer.OrdinalIgnoreCase);

tags.Add("C#");
tags.Add("ASP.NET Core");
tags.Add("c#"); // Duplicate under this comparer

bool exists = tags.Contains("C#");