Редактиране

Споделяне чрез


CA1066: Implement IEquatable when overriding Equals

Property Value
Rule ID CA1066
Title Implement IEquatable when overriding Equals
Category Design
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

A value type (struct) overrides Equals method, but does not implement IEquatable<T>.

Rule description

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

Your System.IEquatable<T>.Equals implementation should return results that are consistent with Equals.

How to fix violations

To fix a violation, implement IEquatable<T> and update 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:

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;
}
using System;

public struct S : IEquatable<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 && Equals(otherS);

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

When to suppress warnings

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

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1066
// The code that's violating the rule is on this line.
#pragma warning restore CA1066

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1066.severity = none

For more information, see How to suppress code analysis warnings.

See also