Unpacking mechanism

When unpacking occurs, a copy of the nested value is entered into the corresponding variable type, but what happens in the boxed memory cell on the heap. Does the box in the box stay in that place and cover the memory in the heap?

+5
source share
2 answers

Does the box in the box stay in that place and cover the memory in the heap?

Yes. In the end, there may be other references to it:

object o1 = 5; object o2 = o1; int x = (int) o1; x = 10; Console.WriteLine(o2); // Still 5 

Weighted values ​​act like ordinary objects in terms of matching garbage collection when there are no stronger references to them.

+4
source

Yes, of course, when unpacking the original is always not affected.

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 type of a value type, the unbox.any command retrieves the value contained in obj (of type O), and therefore the equivalent of unbox, followed by ldobj.

and relatively unbox :

[...] unbox is not required to copy the value type from an object. Usually it just calculates the address of the type of value that is already present inside the box object.

Thus, a copy of the original value may or may not be made, but the original value always remains unchanged.

+3
source

All Articles