JetBrains Rider 2024.3 Help

Code inspection: Values of types marked with 'CannotApplyEqualityOperatorAttribute' should be compared using 'Equals()'

JetBrains Rider 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 !=, JetBrains Rider will issue a warning.

JetBrains Rider 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 JetBrains Rider 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 JetBrains Rider 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: 08 April 2024