Mechanism of Unboxing
Asked Answered
L

2

5

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?

Leban answered 27/5, 2016 at 16:49 Comment(0)
F
4

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.

Flush answered 27/5, 2016 at 16:52 Comment(0)
H
3

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.

Hollander answered 27/5, 2016 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.