Search code examples
c#nullable

How is it that can I execute method on int? set to null without NullReferenceException?


I have read on MSDN that:

The null keyword is a literal that represents a null reference, one that does not refer to any object.

But I've seen the following code running without throwing any exception:

int? i = null;
var s = i.ToString();

So if the variable i is null, why can I execute it's method?


Solution

  • Because int? is actually a Nullable<Int32> and Nullable<T> is a struct, and a structure cannot be null.

    It is just how Nullable types work. They are not reference values, so they can't be null, but they can have a state when they are considered equivalent to null.

    You can get more details about Nullable<T> implementation in how are nullable types implemented under the hood in .net? and Nullable<T> implementation


    Though as pointed by @JeppeStigNielsen there is one case when you can get a NRE:

    However: When boxed to a reference type, special treatment of Nullable<> ensures we do get a true null reference. So for example i.GetType() with i as in the question will blow up with the NullReferenceException. That is because this method is defined on object and not overridable