Search code examples
c#stringcomparison

C# String comparisons: Difference between CurrentCultureIgnoreCase and InvariantCultureIgnoreCase


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?


Solution

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

    MSDN: CultureInfo.InvariantCulture Property

    ... 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. [...]