40

I'm confused by the options of the StringComparison Enumeration. I just want to compare two strings ignoring case. Can someone explain what the terms current culture, invariant culture and ordinal mean? Is there an option common to most use cases, and if so, under what circumstances would the other options be needed?

For reference, the options of the StringComparison enum is as follows:

  • CurrentCulture
  • CurrentCultureIgnoreCase
  • InvariantCulture
  • InvariantCultureIgnoreCase
  • Ordinal
  • OrdinalIgnoreCase
Dan Stevens
  • 6,392
  • 10
  • 49
  • 68
  • Invariant vs Ordinal is explained at http://blogs.msdn.com/b/michkap/archive/2004/12/29/344136.aspx – stuartd Feb 23 '12 at 16:53
  • Good read: https://learn.microsoft.com/en-us/dotnet/csharp/how-to/compare-strings#:~:text=1%20How%20to%20compare%20strings%20in%20C%23%202,to%20specify%20a%20StringComparison%20value%20of%20StringComparison.%20 and https://learn.microsoft.com/en-us/dotnet/api/system.globalization.compareoptions?view=net-6.0 – NoChance Feb 15 '22 at 14:04

2 Answers2

45

If you are comparing two strings for equality then the culture settings don't make much difference (though it affects, for example, Turkish, which has dotted and undotted i's).

If you are sorting a list of strings there's a big difference; different cultures often sort in different orders.

CurrentCulture sorts strings according to, erm, the current culture (i.e. the current locale). So this changes depending on where your software is run.

InvariantCulture is basically US English settings. It's invariant because it's the same wherever your software runs.

Ordinal comparisons are based on the values of the Unicode code points. This is usually the best choice for comparing equality, but not a good choice if you are sorting a list of strings to display to the user.

arx
  • 16,686
  • 2
  • 44
  • 61
  • 2
    Thanks for the explanation. As I'm testing for equality I've gone for `OrdinalIgnoreCase`. – Dan Stevens Feb 24 '12 at 10:46
  • What is the default if StringComparison is not provided? – Dean Kuga Jul 06 '18 at 18:15
  • @DeanKuga The default uses an ordinal comparison: a case-sensitive comparison, and use the current culture. See `https://learn.microsoft.com/en-us/dotnet/csharp/how-to/compare-strings` – Dean Meehan Jun 05 '19 at 08:40
4

See http://blogs.msdn.com/b/abhinaba/archive/2005/10/28/486173.aspx and http://msdn.microsoft.com/en-us/library/ms973919. Recommendation is to use Ordinal* methods.

Shan Plourde
  • 8,528
  • 2
  • 29
  • 42