All rules
CA1066Design Enabled by default: No

Implement IEquatable when overriding Equals

Implement IEquatable when overriding Equals

Microsoft docs

Description

A value type overriding System.Object.Equals method indicates that it supports comparing two instances of the type for value equality. Consider implementing the System.IEquatable1 interface to support strongly typed tests for equality. This ensures that callers performing equality checks invoke the strongly typed System.IEquatable1.Equals method and avoid boxing the argument, improving performance. For more information, see Notes to implementers.

Your System.IEquatable`1.Equals implementation should return results that are consistent with System.Object.Equals.

Cause

A value type (struct) overrides System.Object.Equals method, but does not implement System.IEquatable`1.

How to fix violations

To fix a violation, implement System.IEquatable`1 and update System.Object.Equals override to invoke this implemented method. For example, the following two code snippets show a violation of the rule and how to fix it:

Example

public struct S
{
    private readonly int _value;
    public S(int f)
    {
        _value = f;
    }

    public override int GetHashCode()
        => _value.GetHashCode();

    public override bool Equals(object other)
        => other is S otherS && _value == otherS._value;
}

When to suppress

It is safe to suppress violations from this rule if the design and performance benefits from implementing the interface are not critical.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0