ReSharper 2017.1 Help

Code Inspection: Specify string comparison explicitly

The same as the Specify a culture in string conversion explicitly, this inspection helps avoid problems with running your code on machines with different culture settings.

When stings are compared with the equality operators (== and !=) or the Equals() method, comparison results may differ depending on the machine's locale, the canonical example being the Turkish where there is a lowercase dotless "ı" with the corresponding uppercase "I", and a lowercase "i" with an uppercase "İ" with the dot.

To make clear how exactly the strings will be compared, ReSharper suggests you to use the String.Equals() method overloads to handle casing and culture-aware comparison. For example, a case-insensitive comparison, such as

public void Foo(string a, string b) { if (a.ToUpper() != b.ToUpper()) { } // or if (a.ToLower() != b.ToLower()) { } }
Public Sub Foo(a As String, b As String) If a.ToUpper() <> b.ToUpper() Then End If ' or If a.ToLower() <> b.ToLower() Then End If End Sub

could be replaced with

if (!String.Equals(a, b, StringComparison.CurrentCultureIgnoreCase)) {}
If Not String.Equals(a, b, StringComparison.CurrentCultureIgnoreCase) Then End If

where it is immediately clear that the strings are compared taking the culture settings into consideration.

If the comparison is explicitly made culture-insensitive, then it is also suggested to use String.Equals() with the InvariantCultureIgnoreCase in the comparison rule parameter, e.g.:

if (a.ToLowerInvariant() == b.ToLowerInvariant()) {}
If a.ToLowerInvariant() = b.ToLowerInvariant() Then End If

could be replaced with

if (String.Equals(a, b, StringComparison.InvariantCultureIgnoreCase)) {}
If [String].Equals(a, b, StringComparison.InvariantCultureIgnoreCase) Then End If

See Also

Last modified: 4 July 2017