All rules
CA2251Usage Enabled by default: No

Use String.Equals over String.Compare

Use String.Equals over String.Compare

Microsoft docs

Description

System.String.Compare is designed to produce a total-order comparison that can be used for sorting. If you only care whether the strings are equal, it is both clearer and likely faster to use an equivalent overload of System.String.Equals.

Cause

The result of a call to System.String.Compare is compared to zero.

How to fix violations

To fix violations of this rule, replace the expression comparing the result of System.String.Compare with a call to System.String.Equals.

Example

string leftValue = "...";
string rightValue = "...";

// This code violates the rule.
bool areEqualUsingCompare = string.Compare(leftValue, rightValue, StringComparison.OrdinalIgnoreCase) == 0;

// This code satisfies the rule.
bool areEqualUsingEquals = string.Equals(leftValue, rightValue, StringComparison.OrdinalIgnoreCase);

When to suppress

It is safe to suppress warnings from this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0