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
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.