Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 210
Serenity Avatar asked Sep 12 '10 12:09

Serenity


2 Answers

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.

like image 170
Jon Skeet Avatar answered Oct 07 '22 17:10

Jon Skeet


The expression something.ToUpper().Equals("lowercaseletters") will never be true, so in your example the if-block will not be executed. And of course, this applies to ToLower as well; something.ToLower().Equals("UPPERCASE") will never be true, either.

like image 44
Arve Systad Avatar answered Oct 07 '22 17:10

Arve Systad