C#idiomatic C#
ca2251fundamentals/code-analysis/quality-rules

Code analysis

CA2251: Use `String.Equals` over `String.Compare`

Learn about code analysis rule CA2251: Use String.Equals over String.Compare

CA2251 Usage enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule 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.

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

csharp
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 warnings

It is safe to suppress warnings from this rule.

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.

csharp
#pragma warning disable CA2251
// The code that's violating the rule is on this line.
#pragma warning restore CA2251

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA2251.severity = none

For more information, see How to suppress code analysis warnings.

See also