When unboxing takes place there is the copy of boxed value into an appropriate variable type but what happens at the memory location of the boxed copy on heap. Is boxed copy remain at that location and cover memory on heap?
Is boxed copy remain at that location and cover memory on heap?
Yes. After all, there could be other references to it:
object o1 = 5;
object o2 = o1;
int x = (int) o1;
x = 10;
Console.WriteLine(o2); // Still 5
Boxed values act like normal objects, in terms of being eligible for garbage collection when there are no more strong references to them.
Yes, of course, when unboxing, the original is always unaffected.
Down at the IL level, there are two opcodes for unboxing: unbox.any
and unbox
.
According to MSDN, regarding unbox.any
:
When applied to the boxed form of a value type, the unbox.any instruction extracts the value contained within obj (of type O), and is therefore equivalent to unbox followed by ldobj.
and regarding unbox
:
[...] unbox is not required to copy the value type from the object. Typically it simply computes the address of the value type that is already present inside of the boxed object.
So, a copy of the original value may or may not be made, but the original value always remains unaffected.
© 2022 - 2024 — McMap. All rights reserved.