Cause
A value type (struct) overrides System.Object.Equals method, but does not implement System.IEquatable.
Rule 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.IEquatable interface to support strongly typed tests for equality. This ensures that callers performing equality checks invoke the strongly typed System.IEquatable.Equals method and avoid boxing the argument, improving performance. For more information, see Notes to implementers.
Your System.IEquatable.Equals implementation should return results that are consistent with System.Object.Equals.
How to fix violations
To fix a violation, implement System.IEquatable 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:
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 CA1066To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1066.severity = noneFor more information, see How to suppress code analysis warnings.