Search code examples
c#.netnullnullable

The '.' operator on null nullable


How is it that you can access null nullable's propery HasValue?
I looked to the compiled code, and it's not a syntactic sugar.

Why this doesn't throw NullReferenceException:

int? x = null;
if (x.HasValue)
{...}

Solution

  • That's because int? is short for Nullable<int> which is a value type, not a reference type - so you will never get a NullReferenceException.

    The Nullable<T> struct looks something like this:

    public struct Nullable<T> where T : struct
    {
        private readonly T value;
        private readonly bool hasValue;
        //..
    }
    

    When you assign null there is some magic happening with support by the compiler (which knows about Nullable<T> and treats them special in this way) which just sets the hasValue field to false for this instance - which is then returned by the HasValue property.