C# String comparisons: Difference between CurrentCultureIgnoreCase and InvariantCultureIgnoreCase
-
03-07-2019 - |
Question
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. [...]
OTHER TIPS
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.)