Code inspection: Struct lacks 'IEquatable' implementation (private accessibility)
This inspection suggests that a struct needs implementing the IEquatable<T>
interface to improve performance and reduce memory overhead when comparing instances of this struct in a generic context. The warning is only issued when the struct overrides equality members, and it (or its containing type, such as record) is actually used for equality comparisons.
Implementing IEquatable<T>
in this case will bring the following benefits:
Reduced memory consumption: When
Equals()
is called on a struct that doesn't implementIEquatable<T>
, the runtime converts the value typestruct
to a reference typeobject
, which involves boxing — creating a new object on the heap to hold the value and the necessary metadata.After implementing
IEquatable<T>
, instances of the struct will be compared directly using the custom implementations ofEquals(T other)
orEquals(object obj)
, without converting the struct into an object.Better performance: Implementing
IEquatable<T>
can lead to better performance in collections, such asList<T>
orDictionary<TKey , TValue>
, that use equality comparisons. SinceIEquatable<T>.Equals(T other)
works directly with value types, it is faster compared to struct'sEquals(object)
.
As a quick-fix, JetBrains Rider helps you invoke the equality members generation dialog, which helps implement IEquatable<T>
for your struct.