ReSharper 2024.1 Help

Code Inspection: Compare with '==' types marked by 'CannotApplyEqualityOperatorAttribute'

Category

Constraints Violations

ID

CannotApplyEqualityOperatorToType

EditorConfig

resharper_cannot_apply_equality_operator_to_type_highlighting

Default severity

Warning

Language

C#

Requires SWA

No

ReSharper provides the [CannotApplyEqualityOperator] attribute in ReSharper.Annotations to mark types for which the use of == and != operators is inappropriate and should be replaced with Equals(). Consequently, when two types marked with this attribute are compared using == or !=, ReSharper will issue a warning.

ReSharper assumes that using the equality operators to compare with null is self-evident and will not issue a warning in this case.

[CannotApplyEqualityOperator] class NoEqualityOperators { } class TestEquality { bool Test() { var ne1 = new NoEqualityOperators(); var ne2 = new NoEqualityOperators(); return ne1 == ne2; // warning } }
[CannotApplyEqualityOperator] class NoEqualityOperators { } class TestEquality { bool Test() { var ne1 = new NoEqualityOperators(); var ne2 = new NoEqualityOperators(); return Equals(ne1, ne2); } }

You may also wonder how ReSharper knows which library types cannot be compared with equality operators. Well, the trick is done with external annotations for the .NET Framework Class Library and other frequently used libraries. These annotations are included in the ReSharper installation. The [CannotApplyEqualityOperator] attribute that triggers this inspection can also be used for your custom types, or you can use the mechanism of external annotations to annotate types in other compiled libraries that you use.

Last modified: 15 April 2024