How does the assignment of the null literal to a System.Nullable type get handled by .Net (C#)?

后端 未结 5 1799
情深已故
情深已故 2021-01-13 13:35

I was wondering if anyone knows how the C# compiler handles the following assignment:

int? myInt = null;

My assumption is that there is an

5条回答
  •  鱼传尺愫
    2021-01-13 13:52

    The statement:

    int? myInt = null;
    

    Gets compiled as:

      .locals init (valuetype [mscorlib]System.Nullable`1 V_0)
      IL_0000:  ldloca.s   V_0
      IL_0002:  initobj    valuetype [mscorlib]System.Nullable`1
    

    Which, according to the MSDN, means «Initialize each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.»

    So there's no constructor or conversion here. HasValue will return false, and trying to get its Value will throw an InvalidOperationException. Unless you use GetValueOrDefault of course.

提交回复
热议问题