Understanding values and references

Boxing

As you have just seen, variables of type object can refer to any item of any reference type. However, variables of type object can also refer to a value type. For example, the following two statements initialize the variable i (of type int, a value type) to 42 and then initialize the variable o (of type object, a reference type) to i:

int i = 42;
object o = i;

The second statement requires a little explanation to appreciate what is actually happening. Remember that i is a value type and that it lives on the stack. If the reference inside o referred directly to i, the reference would refer to the stack. However, all references must refer to objects on the heap; creating references to items on the stack could seriously compromise the robustness of the runtime and create a potential security flaw, so it is not allowed. Therefore, the runtime allocates a piece of memory from the heap, copies the value of integer i to this piece of memory, and then refers the object o to this copy. This automatic copying of an item from the stack to the heap is called boxing. The following diagram shows the result:

08fig05.jpg