gdoron
gdoron

Reputation: 150313

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)
{...}

Upvotes: 1

Views: 193

Answers (2)

Hand-E-Food
Hand-E-Food

Reputation: 12814

Like BrokenGlass said, an int? is actually a Nullable<T>.

Structures always contain a value. Usually you cannot set a structure variable to null, but in this special case you can, essentially setting it to default(Nullable<T>). This sets its contents to null rather than the variable itself.

When you set a Nullable<T> to a value, it uses an implicit operator to set Value = value to the new value and HasValue = true.

When you set Nullable<T> to null, it nulls all of the structure's fields. For a bool field such as HasValue, null == false.

Since a Nullable<T> variable is a structure, the variable can always be referenced because its contents is null rather than the variable itself.

There's more information on structures in the Remarks section of the MSDN page struct.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 161012

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.

Upvotes: 12

Related Questions