Archive

Posts Tagged ‘string’

String comparisons in C#

January 19th, 2009

This is my first in the line of note-to-self posts. I don’t know if there will be more. I sure hope there will, ’cause that’d make me remember all the trivia I pick up while scavenging the intar webs.

Anyhow.

I bumped into this semi-useful bit of information while browsing thru stackoverflow. How often do you normalize your strings for case-insensitive comparisons? Quite often, I presume. Well me too.

Turns out, that strings shouldn’t be normalized by calling ToLower() on both sides of the == operator. According to CLR via C#, the ToUpperInvariant() method should be used instead of the ToLowerInvariant(), as stated in chapter 11 of the book:

If you want to change the case of a string’s characters before performing an ordinal comparison, you should use String’s ToUpperInvariant or ToLowerInvariant method. When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons. In fact, the FCL normalizes strings to uppercase prior to performing case-insensitive comparisons.

Whatever that means. I’d like to think that Microsoft has optimized the code for everything.

But there’s a catch. Had I been a C programmer, I would’ve probably thought of this myself, but luckily the comments on stackoverflow alerted me to a valuable realisation:

Don’t do case-insensitive string comparisons with the == operator.

The thing is, ToLower() and ToUpper() methods both have the same pitfall: due to the string type’s immutability, they create another copy of the string into memory.

Use String.Equals(String, String, StringComparison)

In addition to being resource-effective, using  the static Equals method saves you the trouble of checking for null values. Like this, per favore:

string foo = "Foo";
string bar = "foo";
if (String.Equals(foo, bar, StringComparison.OrdinalIgnoreCase))
{
     // ...
}

bookmark bookmark bookmark bookmark bookmark bookmark bookmark

Technology , , , ,