Is there a C# case insensitive equals operator?


Question

I know that the following is case sensitive:

if (StringA == StringB) {

So is there an operator which will compare two strings in an insensitive manner?

1
146
4/7/2010 2:21:55 AM

Accepted Answer

Try this:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
278
3/10/2009 4:54:31 PM

The best way to compare 2 strings ignoring the case of the letters is to use the String.Equals static method specifying an ordinal ignore case string comparison. This is also the fastest way, much faster than converting the strings to lower or upper case and comparing them after that.

I tested the performance of both approaches and the ordinal ignore case string comparison was more than 9 times faster! It is also more reliable than converting strings to lower or upper case (check out the Turkish i problem). So always use the String.Equals method to compare strings for equality:

String.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);

If you want to perform a culture specific string comparison you can use the following code:

String.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);

Please note that the second example uses the the string comparison logic of the current culture, which makes it slower than the "ordinal ignore case" comparison in the first example, so if you don't need any culture specific string comparison logic and you are after maximum performance, use the "ordinal ignore case" comparison.

For more information, read the full story on my blog.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon