Quote:
quote:...does it completly remove from stack and store it into
|
Nope. The unboxed version remains on the stack and can be reused. Here's the blow-by-blow:
Code:
static void Main() {
Int32 v = 1; // Allocate on stack.
Object o = v; // Box the value type (now a reference
// type). The address of the new
// reference type is returned from the
// heap and stored in o.
// v now has two seperate representations. A boxed form on the heap,
// and an unboxed form on the stack. The boxed form will be garbage
// collected. The unboxed form can be reused (the Object variable doesn't
// know it exists), and will be freed when this method terminates.
// The lifetime of the boxed form extends beyond the lifetime of the
// unboxed form.
v = 2; // Change the value of the unboxed form on the
// stack.
}
Here's the generated IL:
Code:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 12 (0xc)
.maxstack 1
.locals init ([0] int32 v,
[1] object o)
// Allocate value type on stack
IL_0000: ldc.i4.1
IL_0001: stloc.0
// Box value type and store the reference
// pointer to the new reference type on the
// heap in the object variable.
IL_0002: ldloc.0
IL_0003: box [mscorlib]System.Int32
IL_0008: stloc.1
// Change the value of the value type
// on the stack.
IL_0009: ldc.i4.2
IL_000a: stloc.0
IL_000b: ret
} // end of method Program::Main
HTH,
Bob