1

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)
{...}
gdoron
  • 147,333
  • 58
  • 291
  • 367

2 Answers2

11

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.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

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.

Community
  • 1
  • 1
Hand-E-Food
  • 12,368
  • 8
  • 45
  • 80
  • 1
    "Setting a structure variable to null sets its contents to null rather than the variable itself." This is wrong - you cannot assign `null` to a value type/struct - with the exception of `Nullable` which the compiler will translate appropriately to setting the `hasValue` field to false. This is only possible because the compiler knows about `Nullable`, hence the "magic" comment. – BrokenGlass Dec 05 '11 at 04:17
  • @BrokenGlass, you're right. I'm used to VB.Net and am currently teaching myself C#. In VB you can assign `Dim x As SomeStructure = Nothing`. I'm guessing this is the same as `SomeStructure x = default(SomeStructure)` rather than `SomeStructure x = null`. – Hand-E-Food Dec 05 '11 at 04:48
  • @gdoron, tricky, given my answer is fundamentally wrong, but I'll give it a shot. :-) – Hand-E-Food Dec 05 '11 at 21:58