Skip to content

Analyzer proposal: Consider using String.Equals instead of String.Compare #45552

Closed
@xtqqczze

Description

@xtqqczze

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

  • Inspiration came from RCS1235: Optimize method call.
  • Proposal was modelled on documentation for CA2249: Consider using String.Contains instead of String.IndexOf.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Globalizationcode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions