Home > Refactorings > Refactorings that work with strings – Use String.Compare

Refactorings that work with strings – Use String.Compare

November 30th, 2011

The Use String.Compare refactoring shipped in DevExpress Refactor! Pro allows you to convert a usual string equality comparison (==) into a more flexible Compare call on the System.String class. Consider the following code:

Use String.Compare refactoring sample code

The refactoring will show you resulting code preview hint:

Use String.Compare refactoring preview

The created String.Compare compares two specified string objects, taking into account their case by passing the boolean “false” as an argument (IgnoreCase), and returns an integer that indicates their relative position in the sort order, indicating whether one string is ordered before another in alphabetical order, or whether it is ordered after or is equivalent.

You can also modify the String.Compare call to take a StringComparison enumeration argument which lets you specify culture-insensitive or case-insensitive comparisons. Only String.Compare call allows you to specify a CultureInfo and perform comparisons using a culture other than the default (current) culture. This argument not only allows you to define the exact comparison behavior you intended, but also makes your code more readable for other developers:

Use String.Compare refactoring resulting code

Also, refer to other refactorings that work with strings.

Products: Refactor! Pro
Versions: 11.2 and up
VS IDEs: any
Updated: Dec/02/2011
ID: R047

Similar Posts: