views:

172

answers:

2

On this page, a commenter writes:

Do NOT ever use .ToUpper to insure comparing strings is case-insensitive.

Instead of this:

type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())) 

Do this:

type.Name.Equals(controllerName + "Controller", 
     StringComparison.InvariantCultureIgnoreCase)

Why is this way preferred?

+2  A: 

In short, it's optimized by the CLR (less memory as well).

Further, uppercase comparison is more optimized than ToLower(), if that tiny degree of performance matters.

In response to your example there is a faster way yet:

String.Equals(type.Name, controllerName + "Controller", 
              StringComparison.InvariantCultureIgnoreCase);
Nick Craver
There's no considerations about weirdness like umlauts, or anything like that? So this guy was just being a dictator about it?
Robert Harvey
@Robert - There are fringe benefits, like free null checking you don't have to worry about, but mainly it's an optimization difference...strings are **highly** optimized by the CLR, so taking advantages of the CLR shortcuts built in can dramatically increase performance if you're hitting that code in a heavy loop. Also, it'll reduce memory overhead as well.
Nick Craver
+2  A: 

Here is the answer in details .. The Turkey Test (read section 3)

As discussed by lots and lots of people, the "I" in Turkish behaves differently than in most languages. Per the Unicode standard, our lowercase "i" becomes "İ" (U+0130 "Latin Capital Letter I With Dot Above") when it moves to uppercase. Similarly, our uppercase "I" becomes "ı" (U+0131 "Latin Small Letter Dotless I") when it moves to lowercase.

Fix: Again, use an ordinal (raw byte) comparer, or invariant culture for comparisons unless you absolutely need culturally based linguistic comparisons (which give you uppercase I's with dots in Turkey)

And according to microsoft you should not even be using the Invariant... but the Ordinal... ( New Recommendations for Using Strings in Microsoft .NET 2.0 )

Gaby
Thanks...I was suspecting something like this. It's irritating when people say you MUST do something a certain way, but they don't say WHY.
Robert Harvey
.. not fond of dictatorships either .. lol .. (*added the microsoft recomendations link*)
Gaby