.NET: Performing case-insensitive string comparison

 Language: C#

Performing string comparisons can be considered as one of the "common" tasks that a programmer needs to do and, more often than not, the comparisons need to be case-insensitive.  The common method taught (or learned, as the case may be) is to convert the entire string to upper case or lower case and perform the comparison accordingly against the appropriate literal.  There's nothing wrong with that method and it has been used since time immemorial.

However, in the .NET environment strings are immutable, and calling the ToLower()/ToUpper() methods of the string class internally creates a new string variable.  A new variable means additional overhead in terms of processor time (the duration consumed during the allocation, creation and assignment of the new variable) and the actual memory consumption of the new variable.  It may not be enough to affect performance, but when you need to squeeze every last bit of available memory for an application, this can become crucial.

So what's the alternative?  Incidentally, the string class provides a static method for performing case-insensitive comparisons without the additional overhead.  It's the Compare method.  It has six overloads but, for the purpose of this mail, i'll just mention one.  The overload we're interested in has the following signature:

    public static int Compare( string strA, string strB, bool ignoreCase)

Equality is indicated by a return value of 0 (zero).  Given this, instead of:

    if (someString.ToUpper() == "VALUE")
we can use this:

    if (string.Compare(someString, "VALUE", true) == 0)

    if (string.Compare(someString, "value", true) == 0)

    if (string.Compare(someString, "vAlUe", true) == 0)


As you can see, it's also less prone to mistakes.  As against to calling ToUpper() and comparing a string to a literal which is composed of lowercase characters by accident.

Other overloads for the Compare method enable developers to specify culture information, compare the substrings of 2 strings, etc.
Please refer to the MSDN documentation for additional information. Link

Published 05-30-2007 3:17 PM by raistlin
Filed under: , ,


# re: .NET: Performing case-insensitive string comparison

In Java we have

String s1 = "";

String s2 = "";


I wonder if it's totally equivalent to what you tried to achieve there in C#...

Wednesday, May 30, 2007 3:05 AM by lamia

# re: .NET: Performing case-insensitive string comparison

@lamia: I think it's safe to assume that they are equivalent. :)

Wednesday, May 30, 2007 10:53 PM by raistlin

# Use String.Compare -- sometimes

Use String.Compare -- sometimes

Thursday, July 19, 2007 8:55 AM by Reggie's Ramblings