Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

The IEqualityComparer<T> interface

Reference for C# IEqualityComparer<T>: implement Equals and GetHashCode to customize Dictionary, HashSet, Distinct and GroupBy, with rules for correct hash codes.

IEqualityComparer<T> (namespace System.Collections.Generic) defines how two values of type T are compared for equality and how a hash code is produced for them. Hash-based collections such as Dictionary<TKey,TValue> and HashSet<T>, and LINQ methods such as Distinct, GroupBy, Except and ToLookup, accept one so that you can change what "the same" means without changing the type itself.

Typical uses are case-insensitive strings, comparing objects by one property, or comparing floating-point values with a tolerance (which, as explained below, is dangerous in a hash).

C#
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
set.Add("Apple");
bool has = set.Contains("APPLE");   // true

Try it

C# A comparer for one property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Built-in comparers and the hash-code rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public interface IEqualityComparer<in T>
{
    bool Equals(T? x, T? y);
    int GetHashCode(T obj);
}
Name Description
x, y The two values to compare. They can be null for reference types (collections normally do not pass null to GetHashCode).
obj The value to hash. Must not be null.

Returns: Equals returns true when the values count as equal. GetHashCode returns an int hash code.

Errors: none defined. A comparer that throws, or that breaks the rules below, leads to missing entries, duplicates or exceptions inside the collection.

Usage notes

  • The contract: Equals must be reflexive, symmetric and transitive, and if Equals(x, y) is true then GetHashCode(x) == GetHashCode(y). Unequal values may share a hash, but fewer collisions are faster.
  • Hash what you compare. If Equals looks at City, GetHashCode must use only City. Use HashCode.Combine(a, b) for several fields.
  • Do not mutate hashed fields while an object is a key; the entry becomes unreachable.
  • No tolerance comparers in hash collections. "Equal within 0.001" is not transitive and cannot be hashed consistently. Use SortedSet<T> with an IComparer<T> for that.
  • Built-ins: StringComparer.Ordinal, OrdinalIgnoreCase and InvariantCulture... (see StringComparer), and EqualityComparer<T>.Default, which uses IEquatable<T> when present. Records generate value equality for you.
  • Create one inline with EqualityComparer<T>.Create(equals, getHashCode) (.NET 8) when a small lambda is enough.
  • Comparers are not ordering. For sorting use IComparer<T>.
  • Contravariant: IEqualityComparer<object> can be used where IEqualityComparer<string> is expected.