Stuff that's in my head

Can open... Worms? everywhere! The blog of Colin Angus Mackay
posts - 379, comments - 486, trackbacks - 51

Tip of the day #13 (String Equality)

When comparing two strings in a case insensitive manner, use:

myFirstString.Equals(mySecondString, StringComparison.InvariantCultureIgnoreCase)

or, if cultural rules are to be ignored completely* then use:

myFirstString.Equals(mySecondString, StringComparison.OrdinalIgnoreCase)

over:

myFirstString.ToLower() == mySecondString.ToLower()

* The invariant culture is actually a non-region specific English language culture. The ordinal comparison is faster than any culture specific comparison as it uses a much simpler comparison algorithm.

Print | posted on Sunday, July 12, 2009 11:19 AM

Feedback

Gravatar

# re: Tip of the day #13 (String Comparison)

String.Compare(String1,String2,false) would be more efficient and recommended practice, right?
7/14/2009 5:11 AM | Navaneeth
Gravatar

# re: Tip of the day #13 (String Comparison)

I think the title of my post may have caused some confusion. I mean string equality. Comparison is a slightly different concept - although you can, oviously, do an equality check with String.Compare.

Incidentally, String.Compare(String1,String2,false) uses the current cultural as part of the comparison so it has to process cultural rules in order to achieve its result. Of course, if you want a culturally specific comparison then that's fine, most of the time I find myself comparing strings (as in checking equality) in internal lookups and so on, where cultural rules are not required. In that sort of situation you want the comparison to be fast so you want to turn off culture rules all together, hence using the OrdinalIgnoreCase rule.
7/14/2009 8:13 PM | Colin Mackay

Post Comment

Title  
Name  
Email
Url
Comment   

Powered by: