views:

235

answers:

4

When using the String.Equals(string a, string b, StringComparison comparisonType) and not caring about the case of 'a' and 'b', what's the proper StringComparison to use? In other words, what's the difference between StringComparison.CurrentCultureIgnoreCase, StringComparison.InvariantCultureIgnoreCase, and StringComparison.OrdinalIgnoreCase, and how will each one affect the use of String.Equals?

A: 

This MSDN page gives the details, but no examples.

ChrisF
A: 

The thing is that uppercase versions of lowercase letters are not same in all languages. For example, uppercase of "u" is "U" in en-us, but it may be something else in some other culture.

Try this, for example:

        CultureInfo english = new CultureInfo("en-US", false);
        CultureInfo turkish = new CultureInfo("tr-TR", false);

        foreach (String i in new String[] { "a", "e", "i", "o", "u" })
        {
            String iEng = i.ToUpper(english);
            String iTur = i.ToUpper(turkish);
            Console.Write(i); 
            Console.WriteLine(iEng == iTur ? " Equal" : " Not equal");
        }

        Console.ReadLine();

So if you have strings entered in current thread's culture, containing such letters, using invariant culture might give wrong results. So I would use CurrentCultureIgnoreCase, if you are sure that the compared strings were entered in current culture and should be compared that way also.

Groo
A: 

I highly recommend reading this article, as it explains all the fun issues when comparing strings.

http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html

jvenema