tags:

views:

125

answers:

4
+11  Q: 

Nullable ToString()

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?

+7  A: 

I think that many people have such checks because it is not a natural behavior of an object that can hold null value.

Andrew Bezzub
@Andrew, agreed, because people (like me) think at first that it will throw an exception.
Nathan Koop
I had no idea this was the behavior. I definitely would have thought that any construct which returns true for (x == null) would also throw a NullReferenceException if you call x.ToString().
Dan Bryant
+1  A: 

may be it is just to follow pattern? or they don't know the backend. you are right code is exactly same. you can even do:

int? i = null;
i.ToString(); //No NullReferenceException
Andrey
+1  A: 

No, you're correct, the shorter version is the same as what other folks have done in that regard. The other construct I tend to use a lot instead of the ternary with nullables is the null coalescing operator,. which also protects you from nulls. For ToString() it's not necessary (as you pointed out) but for default int values (for example) it works nicely, e.g.:

int page = currentPage ?? 1;

that lets you do all the integer operations on page w/o first explicitly null checking and calling for the value in currentPage (where currentPage is an int? perhaps passed as a param)

Paul
+2  A: 

You seem to be 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 NullReferenceException, although here it doesn't happen.

Thomas Wanner
Actually, at least two people noticed: Eric Lippert and Johannes Rössel.
Jon Skeet