-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Globalizationcode-analyzerMarks an issue that suggests a Roslyn analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixerMarks an issue that suggests a Roslyn code fixer
Milestone
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.
Additional context
scalablecory and NewellClarkjamescanadyGSPP
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Globalizationcode-analyzerMarks an issue that suggests a Roslyn analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixerMarks an issue that suggests a Roslyn code fixer