views:

1630

answers:

3

When doing a string comparison in C#, what is the difference between doing a

string test = "testvalue";
test.Equals("TESTVALUE", StringComparison.CurrentCultureIgnoreCase);

and

string test = "testvalue";
test.Equals("TESTVALUE", StringComparison.InvariantCultureIgnoreCase);

... and is it important to include that extra parameter, anyway?

+2  A: 

Check out this link to a very similar question

cgreeno
+6  A: 

Microsoft gives some decent guidance for when to use the InvariantCulture property:

http://msdn.microsoft.com/en-us/library/4c5zdc6a.aspx

... an application should use the invariant culture only for processes that require culture-independent results, such as formatting and parsing data that is persisted to a file. In other cases, it produces results that might be linguistically incorrect or culturally inappropriate.

Security Considerations

If a security decision will be made based on the result of a string comparison or case change, your application should use an ordinal comparison that ignores case instead of using InvariantCulture. [...]

String Operations

If your application needs to perform a culture-sensitive string operation that is not affected by the value of CurrentCulture, it should use a method that accepts a CultureInfo parameter. [...]

Persisting Data

The InvariantCulture property is useful for storing data that will not be displayed directly to users. Storing data in a culture-independent format guarantees a known format that does not change. When users from different cultures access the data, it can be formatted appropriately based on specific user. [...]

Michael Burr
+8  A: 

The other posts have given good advice, but I thought it might be nice to show an example of where it definitely makes a difference:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()
    {
        CultureInfo turkish = CultureInfo.CreateSpecificCulture("tr");
        Thread.CurrentThread.CurrentCulture = turkish;                

        // In Turkey, "i" does odd things
        string lower = "i";
        string upper = "I";

        Console.WriteLine(lower.Equals(upper, 
            StringComparison.CurrentCultureIgnoreCase));
        Console.WriteLine(lower.Equals(upper, 
            StringComparison.InvariantCultureIgnoreCase));
    }
}

(There are no doubt many other cases - this was just the first one I thought of.)

Jon Skeet
Yes, the turkish i is a special case. They have a lowercase dotless "ı" with an uppercase "I", and a lowercase "i" with an uppercase "İ". It is considered the canonical case for culture differences.
configurator
For more on the nature of Turkish as the "canonical case" mentioned by configurator, see: http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html
JeffH