C#idiomatic C#
ca1067fundamentals/code-analysis/quality-rules

Code analysis

CA1067: Override Equals when implementing IEquatable

Learn about code analysis rule CA1067: Override Equals when implementing IEquatable

CA1067 Design enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A type implements System.IEquatable, but does not override System.Object.Equals method.

Rule description

A type implementing System.IEquatable interface indicates that it supports comparing two instances of the type for equality. You should also override the base class implementations of System.Object.Equals and System.Object.GetHashCode methods so that their behavior is consistent with that of the System.IEquatable.Equals implementation. For more information, see Notes to implementers.

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

How to fix violations

To fix a violation, override System.Object.Equals and implement it by invoking the System.IEquatable.Equals implementation. For example, the following two code snippets show a violation of the rule and how to fix it:

csharp
using System;

public struct S : IEquatable<S>
{
    private readonly int _value;
    public S(int f)
    {
        _value = f;
    }

    public bool Equals(S other)
        => _value == other._value;
}
csharp
using System;

public struct S : IEquatable<S>
{
    private readonly int _value;
    public S(int f)
    {
        _value = f;
    }

    public bool Equals(S other)
        => _value == other._value;

    public override bool Equals(object obj)
        => obj is S objS && Equals(objS);

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

When to suppress warnings

Do not suppress violations of this rule.

See also