C#: Confusion about ToUpper() and ToLower()

Serenity picture Serenity · Sep 12, 2010 · Viewed 15.7k times · Source

if I do something like this...

String myVar = "in";
if(myVar.ToUpper() == "in")
{
    //do something
}

This is not going to go inside "if" block ..right?

or

Is it going to check BOTH for "in" AND "IN" and do whatever is there inside that if? If so, why is that ? Isn't it supposed to skip what's inside of "if" block?

Same confusion is about ToLower() too

Edit: So to check for both cases, I need to write:

if((myVar.ToUpper().Equals("in"))&&(myVar.Equals("in")))

Like this..right?

Answer

Jon Skeet picture Jon Skeet · Sep 12, 2010

Rather than converting to upper case and then comparing, you should use an equality comparison which can be made case-insensitive. For example:

if (myVar.Equals("in", StringComparison.OrdinalIgnoreCase))
{
     ...
}

You should consider carefully exactly which rules are appropriate - ordinal, the current culture, the invariant culture, or possibly another culture entirely (e.g. using StringComparer.Create(culture, true)).

For more details around this, read the MSDN Best Practices for Using Strings in the .NET Framework article.