C# Interview Question #128

What is IEqualityComparer<T> in C#?

Advanced LINQ, Expressions & Collections Senior Advanced

Quick Interview Answer

IEqualityComparer<T> defines custom equality and hash-code logic for a type without changing the type itself.

Detailed Explanation

IEqualityComparer<T> defines custom equality and hash-code logic for a type without changing the type itself.

It is commonly supplied to Dictionary<TKey,TValue>, HashSet<T>, Distinct, GroupBy, and other APIs where custom equality rules are required.

For strings, built-in comparers such as StringComparer.OrdinalIgnoreCase are usually preferable to writing a custom comparer.

Code Example

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

emails.Add("USER@example.com");

bool exists =
    emails.Contains("user@example.com"); // true