dotnet / dotnet/dotnet-api-docs

Misleading remarks on IEquatable<T> Interface

Open
#9,631 0 comments 0 reactions 0 assignees View on GitHub
area-System.Runtime Pri3 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

Hello,

I found the [remarks of the IEquatable Interface](https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=net-8.0#remarks) misleading:

_The IEquatable interface is used by generic collection objects such as Dictionary, List, and LinkedList when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove. **It should be implemented for any object that might be stored in a generic collection**._

I'm missing the hint, that this is not true for immutable reference types, as mentioned in the _Guidelines for reference types_ from [Supplemental API remparks > Equals method](https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-object-equals):

_**You should not override Equals on a mutable reference type.** This is because overriding Equals requires that you also override the GetHashCode method, as discussed in the previous section. This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table._

I have a "data" class which is mutable and will be stored in List collections. Following the remark on the IEquatable documentation:

_... It should be implemented for any object that might be stored in a generic collection ..._

I implemented the IEquatable interface for class. The [CA1067](https://learn.microsoft.com/de-de/dotnet/fundamentals/code-analysis/quality-rules/ca1067) and the [Notes to Implementers](https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=net-8.0#notes-to-implementers):

_... If you implement IEquatable, you should also override the base class implementations of Equals(Object) and GetHashCode() ..._

forces me to override also the Equals(Object) and GetHashCode(). But digging deeper, I found that this should only be done for immutable data.

A hint in the remarks of the IEquatable interface would have saved me a lot of time. (Good, so I have developed a better understanding of Equals ;) )

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.