Home

IEqualityComparerTKey

IEqualityComparerTKey is not the canonical name used in the standard API; in the widely used .NET libraries the generic interface is IEqualityComparer<TKey>. The term IEqualityComparerTKey may appear as a shorthand or misnomer for that interface, but the official API defines it as IEqualityComparer<TKey>. This interface is used to supply custom logic for determining equality and computing hash codes for keys of type TKey.

The interface IEqualityComparer<TKey> defines two members: bool Equals(TKey x, TKey y) and int GetHashCode(TKey obj). Implementations

Usage of IEqualityComparer<TKey> occurs primarily with generic collections that rely on hashing, such as Dictionary<TKey, TValue>

Common patterns include using existing comparers provided by the framework (for example, StringComparer.OrdinalIgnoreCase for string keys)

must
provide
a
consistent
equality
relation
and
a
hash
function
such
that
if
Equals(x,
y)
is
true,
then
GetHashCode(x)
equals
GetHashCode(y).
Hash
codes
should
be
fast
to
compute
and
spread
values
well
to
minimize
collisions.
The
behavior
should
be
stable
for
objects
used
as
keys,
and
the
implementation
should
avoid
throwing
exceptions
in
common
comparisons.
and
HashSet<T>.
By
supplying
a
comparer
to
these
collections,
you
can
customize
how
keys
are
compared
and
how
their
hash
codes
are
generated.
This
enables
scenarios
such
as
case-insensitive
string
matching,
culture-aware
comparisons,
or
domain-specific
identity
rules
for
complex
key
types.
or
implementing
a
custom,
stateless
comparer
that
encapsulates
the
specific
equality
criteria.
When
implementing
your
own
comparer,
ensure
it
remains
immutable
and
thread-safe
if
shared
across
multiple
collections.
See
also
IEqualityComparer<T>,
StringComparer,
Dictionary<TKey,
TValue>,
and
HashSet<T>
for
related
concepts.