.NET: Performing case-insensitive string comparison
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