Search code examples
c#structnull

Assigning null value to nullable value type is equal to new Nullable<T> in c#?


Assigning null value to nullable value type is equal to new Nullable<T> in c#?

I've the following code:

int? num = null;

According to the this answer:

The nullable type is a struct consisting of two fields: a bool and a T. When the value is null, the bool is false and the T has the default value. When the value is not null, the bool is true.

The default value for value types is set for the Value field in Nullable<T> struct. ^

When I use the int? num = null, the num is equal to new Nullable<int>(); and default value 0 is set for the value?


Solution

  • When I use the int? num = null, the num is equal to new Nullable(); and default value 0 is set for the value?

    Yes, but you'll get an InvalidOperationException if you attempt to access the Value property of a Nullable<T> when it's HasValue property is false.

    Eric Lippert wrote a two-posts series about Nullable types in his blog, I highly recommend reading it:

    Nullable micro-optimizations, part one

    Nullable micro-optimizations, part two

    More Information: