Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

string comparison - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...