ToLower vs ToLowerInvariant

6.7k views Asked by At

I'm just looking for any example that this two methods produces different results. First of all, I visit msdn page, and run code from it with minor changes

using System;
using System.Globalization;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] words = { "Tuesday", "Salı", "Вторник", "Mardi", 
                         "Τρίτη", "Martes", "יום שלישי", 
                         "الثلاثاء", "วันอังคาร" };
        Console.BufferHeight = 1000;
        var test = CultureInfo.GetCultures(CultureTypes.AllCultures)
                              .Select(ci =>
                                      {
                                          string[] wordsToLower = words.Select(x => x.ToLower(ci)).ToArray();
                                          string[] wordsToLowerInvariant = words.Select(x => x.ToLowerInvariant()).ToArray();
                                          return new
                                                 {
                                                     Culture = ci,
                                                     ToLowerDiffers = !wordsToLower.SequenceEqual(wordsToLowerInvariant)
                                                 };
                                      })
                              .ToArray();
        foreach (var x in test)
        {
            Console.WriteLine("Culture {0}, ToLower and ToLowerInvariant produces different results: {1}", x.Culture, x.ToLowerDiffers);
        }
        Console.WriteLine();
        Console.WriteLine("Difference exists for any ToLower call: {0}", test.Any(x => x.ToLowerDiffers));
    }
}

But here I have a problem: this code produces the same output for ToLower and ToLowerInvariant calls in all existing cultures.

So question is: there is any string that produces different results for this test?

2

There are 2 answers

1
Matthew Watson On BEST ANSWER

Try the Turkish dotted İ:

var culture = new CultureInfo("tr-TR");

string test = "İ";

if (test.ToLower(culture) == test.ToLowerInvariant())
    Console.WriteLine("Same");
else
    Console.WriteLine("Different"); // Prints this!
2
Gökhan Uslu On

xxxInvariant assumes culture setting as default. To be able to show the difference, you should demonstrate ToLower and ToLowerInvariant with a culture info that is different than the default culture in your setting. And by default, the default culture is the system culture.

So if your system's culture is en-US and you use only en-US characters in your code, ToLower and ToLowerInvariant will give the same result.

As far as I can tell, if you change "Salı" to "SALI" after ToLowerInvariant you should get "Sali".