Which is generally best to use -- StringComparison.OrdinalIgnoreCase or StringComparison.InvariantCultureIgnoreCase?

Dave Haynes picture Dave Haynes · Sep 16, 2008 · Viewed 63.9k times · Source

I have some code like this:

If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then
    DoSomething()
End If

I don't care about the case. Should I use OrdinalIgnoreCase, InvariantCultureIgnoreCase, or CurrentCultureIgnoreCase?

Answer

Robert Taylor picture Robert Taylor · Sep 16, 2008

Newer .Net Docs now has a table to help you decide which is best to use in your situation.

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.