dotnet / dotnet/dotnet-api-docs

Enumerable.Distinct requires the GetHashCode override to work on default comparer

Open
#3,572 1 comment 0 reactions 0 assignees View on GitHub
area-System.Linq help wanted Pri3
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

The docs say (https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?view=netframework-4.8#System_Linq_Enumerable_Distinct__1_System_Collections_Generic_IEnumerable___0__)

>If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the `IEquatable` generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide `GetHashCode` and `Equals` methods.

This is confusing and wrong. `IEquatable` interface only (!) requires to implement the `bool Equals(T other);` method. However, inside `Distinct()` (and probably other similar methods such as group by, etc) also compares the hash codes of the object, which it takes from the `EqualityComparer.Default`, which, while being created for an implementation of `IEquatable`, that does not have the override for `GetHashCode(T object)`, uses the default `T.GetHashCode()`.

Consequence: if I follow the "must" part of the doc and implement ONLY `IEquatable` interface, that method (`bool Equals(T other);`) even isn't being called! Which naturally totally confuses me as for what did I do wrong.

How to fix: TBH I'd say the implementation here with `IEquatable` itself is very questionable. It should've been IEqualityComparer. But for the docs, please at least add the note that "If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the `IEquatable` generic interface in the class **AND override the inherited `GetHashCode()` method. For consistency, after that you should also override the inherited `Equals()` method.** ..."

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.