Boxing/Unboxing and Nullable?

后端 未结 3 1607
遇见更好的自我
遇见更好的自我 2021-01-05 05:22

I understand that boxing and unboxing is about casting (real type to object... object to real type). But I do not understand what the MSDN say about it with the Nullable. He

相关标签:
3条回答
  • 2021-01-05 05:50

    What it's saying is that if you do:

    int? x = 5;
    object y = x; // Boxing
    

    You end up with a boxed int, not a boxed Nullable<int>. Similarly if you do:

    int? x = null; // Same as new Nullable<int>() - HasValue = false;
    object y = x; // Boxing
    

    Then y ends up as a null reference.

    0 讨论(0)
  • 2021-01-05 05:55

    If a Nullable<T> is null, it'll be boxed as a null reference and will not behave as a boxed value type with HasValue = true.

    In fact, to implement this feature, it was required that CLR intrinsically support Nullable<T> type and treat it differently. Developers can not write their own type that works like Nullable<T>.

    It's worth noting that this was one of the late .NET 2.0 features. In early betas, Nullable<T> behaved just like a normal structure. In final release, it was changed to box to null reference. This change was specifically breaking for SQL Server CLR team and they had to change some fundamental stuff for it.

    0 讨论(0)
  • 2021-01-05 06:13

    What that means is that if you do:

    int? i = 5;
    object o = i;
    

    it is an "int" (5) that is boxed, not an "int?" (5). If x had been null (!HasValue), o would be null, not a box around an empty "int?"

    Then when you unbox:

    i = (int?)o;
    

    If o is null, i becomes an empty "int?"; otherwise, the 5 is unboxed and used to create an "new int?(5)".

    Basically, you shouldn't (short of cheating) be able to get a boxed nullable<T> directly - only a boxed T

    0 讨论(0)
提交回复
热议问题