Boxing vs Unboxing

前端 未结 6 1982
暖寄归人
暖寄归人 2021-02-01 16:48

Another recent C# interview question I had was if I knew what Boxing and Unboxing is. I explained that value types are on Stack and reference types on Heap. When a value is cast

6条回答
  •  不要未来只要你来
    2021-02-01 17:06

    I was expecting to see b == 2 as well, but it isn't, why? is it because the second boxing destroys and replaces the whole (a)-object on heap?

    No, not exactly. It leaves the object as it is on the heap (as the b variable is also referencing it) and creates a new object for the new value, which the a variable will reference.

    You are right that your second example does not use boxing. You can't access a value that is boxed in any other way than unboxing it, so there is no way to change a boxed value.

    Not even a mutable struct like Point can be changed when boxed. To access the properties of the struct you have to unbox it, so you can't change the boxed struct in place.

提交回复
热议问题