tags:

views:

4208

answers:

5

If I have some code like this:

If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then ' .. do something ..

And I don't care about the case, should I use OrdinalIgnoreCase, InvariantCultureIgnoreCase, or CurrentCultureIgnoreCase?

A: 

It depends on what you want, though I'd shy away from invariantculture unless you're very sure you'll never want to localize the code for other languages. Use CurrentCulture instead.

Also, OrdinalIgnoreCase should respect numbers, which may or may not be what you want.

Joel Coehoorn
Ever wrote VB6 code in a mixed-language environment? You can create code that compiles on a PC with the french locale but won't compile on PCs with the english locale, because any numbers stored in the form resources use the format of the current locale. I'd argue you need to take the opposite approach: be very careful when you use the current culture. Always think about whether your system will still work when its data moves between cultures. Same thing with timezones.
Wim Coenen
+4  A: 

MSDN makes some pretty clear recommendations about this: http://msdn.microsoft.com/en-us/library/ms973919.aspx

chessguy
+24  A: 

From MSDN's "New Recommendations for Using Strings in Microsoft .NET 2.0"

Summary: Code owners previously using the InvariantCulture for string comparison, casing, and sorting should strongly consider using a new set of String overloads in Microsoft .NET 2.0. Specifically, data that is designed to be culture-agnostic and linguistically irrelevant should begin specifying overloads using either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase members of the new StringComparison enumeration. These enforce a byte-by-byte comparison similar to strcmp that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance. (15 printed pages)

Robert Taylor
+1  A: 

I guess it depends on your situation. Since ordinal comparisons are actually looking at the characters' numeric Unicode values, they won't be the best choice when you're sorting alphabetically. For string comparisons, though, ordinal would be a tad faster.

Bullines
A: 

I reopen this thread because the framework 4 did some change.

OrdinalIgnoreCase are really slow on framework 4 but increase speed in invariantculture.

Does anyone have noticed this change?

baz