संपादित करें

इसके माध्यम से साझा किया गया


CA1067: Override Equals when implementing IEquatable

Property Value
Rule ID CA1067
Title Override Equals when implementing IEquatable
Category Design
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As suggestion

Cause

A type implements IEquatable<T>, but does not override Equals method.

Rule description

A type implementing IEquatable<T> interface indicates that it supports comparing two instances of the type for equality. You should also override the base class implementations of Equals and GetHashCode() methods so that their behavior is consistent with that of the System.IEquatable<T>.Equals implementation. See here for more details.

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

How to fix violations

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

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