Search code examples
c#nullnullablevalue-typereference-type

Reference types vs Nullable types ToString()


Could someone please be kind enough to explain why calling ToString() on an empty reference type causes an exception (which in my mind makes perfect sense, you cant invoke a method on nothing!) but calling ToString() on an empty Nullable(Of T) returns String.Empty? This was quite a surprise to me as I assumed the behaviour would be consistent across types.

Nullable<Guid> value = null;
Stock stock = null;
string result = value.ToString(); //Returns empty string
string result1 = stock.ToString(); //Causes a NullReferenceException

Solution

  • Nullable<T> is actually a struct that has some compiler support and implementation support to behave like a null without actually being null.

    What you are seeing is the collision between the implementation allowing you to treat it naturally as a null as you would any other reference type, but allowing the method call to happen because the Nullable<T> isn't actually null, the value inside it is null.

    Visually it looks like it shouldn't work, this is simply because you cannot see what is done in the background for you.

    Other such visual trickery can be seen when you call an extension method on a null reference type... the call works (against visual expectation) because under the hood it is resolved into a static method call passing your null instance as a parameter.

    How does a Nullable<T> type work behind the scenes?