ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Specify string comparison explicitly

Last modified: 11 February 2024

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

When string results returned by String.ToUpper()/String.ToLower() are compared using equality operators (==/!=), comparison results may differ depending on the machine's locale. The canonical example is the Turkish where there is a lowercase dotless "ı" with the corresponding uppercase "I", and a lowercase "i" with an uppercase "İ" with the dot.

So in a case of using String.ToUpper()/String.ToLower() for a case-insensitive comparison:

public void Foo(string a, string b)
{
  if (a.ToUpper() != b.ToUpper()) { }

  // or

  if (a.ToLower() != b.ToLower()) { }
}

ReSharper suggests replacing it with an overload of String.Equals():

if (!String.Equals(a, b, StringComparison.CurrentCultureIgnoreCase)) {}

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, for example:

if (a.ToLowerInvariant() == b.ToLowerInvariant()) {}

could be replaced with

if (String.Equals(a, b, StringComparison.InvariantCultureIgnoreCase)) {}