3

z contains NULL. Why doesn't the output window show the NULL? Is it because NULL is not a value?

int? x = null;
int? y = 1;
int? z = 0;
z = x + y;
Debug.WriteLine(z);

Output window does not show null

5
  • 3
    What would that look like exactly? May 1, 2018 at 19:49
  • Debug.WriteLine((object)z ?? "null"); May 1, 2018 at 19:52
  • Thank you Olivier. I actually wanted to know why the output doesn't display null. Just curious. May 1, 2018 at 19:54
  • 2
    Use the source, Luke.
    – Kenneth K.
    May 1, 2018 at 19:55
  • It's like asking someone to give an answer to a question you haven't asked. The answer doesn't exist, how could it be said? May 1, 2018 at 19:58

1 Answer 1

9

When you look into the reference source of Console.WriteLine(Object), you can see that .NET calls System.IO.TextWriter.WriteLine(Object) which does explicitly check for null and will then output a blank line:

public virtual void WriteLine(Object value) {
    if (value==null) {
        WriteLine();
    }
    else {
        // Call WriteLine(value.ToString), not Write(Object), WriteLine().
        // This makes calls to WriteLine(Object) atomic.
        IFormattable f = value as IFormattable;
        if (f != null)
            WriteLine(f.ToString(null, FormatProvider));
        else
            WriteLine(value.ToString());
    }
}

Debug.WriteLine(Object) behaves the same way but is a bit more complicated. It eventually calls System.Diagnostics.TraceListener.WriteLine(Object).

3
  • 1
    Basically the answer is because the implementors decided NULL is converted to an empty string in the case of int?.ToString(). May 1, 2018 at 20:08
  • You are correct, it prints a blank line. I hadn't noticed that. I would have thought it would print NULL, because when I debug the value of z, it shows null. At the same time null is not a value, so I guess it makes sense for output to not show it. May 1, 2018 at 20:14
  • YMMV. Try the same thing with String a = null;Debug.WriteLine(a);. Beware the virtual. May 1, 2018 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.