Closed
Description
Category: Microsoft.Usage
Fix is breaking or non-breaking: Non-breaking
Cause
This rule locates calls to Compare
where the result is used to check for equality, and suggests using Equals
instead, to improve readability.
Rule description
When Compare is used to check if the result is equal to 0
, the call can be safely substituted with Equals.
Overload | Suggested fix |
---|---|
String.Compare(string) |
String.Equals(string) |
String.Compare(string, false) |
String.Equals(string, StringComparison.CurrentCulture) |
String.Compare(string, true) |
String.Equals(string, StringComparison.CurrentCultureIgnoreCase) |
String.Compare(string, StringComparison) |
String.Equals(string, StringComparison) |
Examples
Code with Diagnostic
string.Compare(x, y) == 0
string.Compare(x, y) != 0
string.Compare(x, y, false) == 0
string.Compare(x, y, true) == 0
string.Compare(x, y, StringComparison.CurrentCulture) == 0
Code with Fix
string.Equals(x, y)
!string.Equals(x, y)
string.Equals(x, y, StringComparison.CurrentCulture)
string.Equals(x, y, StringComparison.CurrentCultureIgnoreCase)
string.Equals(x, y, StringComparison.CurrentCulture)
When to suppress warnings
It's safe to suppress a violation of this rule if improving code readability is not a concern.