A value type (struct) overrides Equals method, but does not implement IEquatable<T>.
Rule descriptionA 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 Notes to implementers.
Your System.IEquatable<T>.Equals implementation should return results that are consistent with Equals.
How to fix violationsTo 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 warningIf 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 alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4