Search code examples
c#nullnullable

Nullable initialized to null - understanding the source code


I was looking at the following code for the .NET Nullable<T> class: http://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e

And I was wondering, what would be its behavior for the following use:

int? x = null;

Obviously, x.hasValue() returns false, however I see that in the constructor, hasValue property is always set to true.

So what am I missing?


Solution

  • "the constructor", yes, the constructor that is explicitly written for Nullable<T>, however all structs have one additional constructor, a parameterless default constructor that you're not allowed to implement. This will always be present.

    So you can think of the code from your question as similar to this:

    int? x = new Nullable<int>();
    

    In fact, if we compile your code and my code and look at the generated IL:

    Your code:

    IL_0001:  ldloca.s    00 // a
    IL_0003:  initobj     System.Nullable<System.Int32>
    

    My code:

    IL_0001:  ldloca.s    00 // a
    IL_0003:  initobj     System.Nullable<System.Int32>
    

    So they're completely identical.

    The default constructor for a struct initializes all fields to byte-wise zeroes, which equates to false for bool fields, 0 for number fields, null for reference type fields, etc.