3

Using left.ToUpper() == right.ToUpper() is not the best option to compare strings, at least because of Performance issues. I want to refactor (fully preserving behavior!) this code, to something efficient, but can't achieve full equivalency for the special case.

So, here is a simple test method:

[TestCase("Strasse", "Straße", "tr-TR")]
[TestCase("İ", "i", "tr-TR")]
public void UsingToUpper_AndCurrentCultureIgnoreCase_AreSame(string left, string right, string culture)
{
    // Arrange, Act
    Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
    var toUpper = left.ToUpper() == right.ToUpper();
    var stringComparison = left.Equals(right, StringComparison.CurrentCultureIgnoreCase);

    // Assert
    Assert.AreEqual(toUpper, stringComparison);
}

I tried two options, StringComparison.CurrentCultureIgnoreCase and StringComparison.OrdinalIgnoreCase both of them fails (in different cases).

So, the question:

Is there a way to compare two strings, without changing case and fully preserve the behavior of ToUpper()?

Vladimir
  • 2,082
  • 1
  • 13
  • 27
  • Looking at your test cases, you expect the first test case to be true to be successful as well as the second to be true? Because ToUpper fails in the first case while stringComparison is successfull, would you expect them to be true? and in the second case both are true. – vsarunov May 17 '19 at 08:45
  • I expecting to have the same behavior. Current task is to refactor legacy code, containing string compare with `ToUpper()` to something more efficient. Multiple consumers use this code, and we want to be sure that nothing will be broken. – Vladimir May 17 '19 at 08:51

1 Answers1

0

You would have to write your own custom Comparison method I am afraid.

ToUpper is making use of the Unicode metadata. Every character (Unicode code point) has a case as well as case mapping to upper- and lowercase (and title case). .NET uses this information to convert a string to upper- or lowercase. You can find the very same information in the Unicode Character Database.

You can supply a culture to the ToUpper method, but this would not be your goal. You can write your own customCulture like defined in this answer: Create custom culture in ASP.NET

However, there would not be any similar behaviour to the ToUpper method as mentioned before it uses Unicode metadata. You cannot force string Equals to use Unicode Characters.

vsarunov
  • 1,433
  • 14
  • 26