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

Categories

I see everywhere constructions like:

int? myVar = null;
string test = myVar.HasValue ? myVar.Value.ToString() : string.Empty;

Why not use simply:

string test = myVar.ToString();

Isn't that exactly the same ? At least Reflector says that:

public override string ToString()
{
  if (!this.HasValue)
  {
    return "";
  }
  return this.value.ToString();
}

So, is that correct (the shorter version) or am I missing something?

See Question&Answers more detail:os

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

1 Answer

You are quite correct. Also in this question, the former solution is suggested while nobody actually notices ToString() already gives the correct answer.

Maybe the argument for the more verbose solution is readability: When you call ToString() on something that is supposed to be null, you usually expect a NullReferenceException, although here it isn't thrown.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...