ReSharper 2024.3 Help

Code inspection: Struct lacks 'IEquatable' implementation (non-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 implement IEquatable<T>, the runtime converts the value type struct to a reference type object, 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 of Equals(T other) or Equals(object obj), without converting the struct into an object.

  • Better performance: Implementing IEquatable<T> can lead to better performance in collections, such as List<T> or Dictionary<TKey , TValue>, that use equality comparisons. Since IEquatable<T>.Equals(T other) works directly with value types, it is faster compared to struct's Equals(object).

As a quick-fix, ReSharper helps you invoke the equality members generation dialog, which helps implement IEquatable<T> for your struct.

Last modified: 08 August 2024