Previous Page
Next Page

Boxing

As you have just seen, variables of type object can refer to any object of any reference type. That is, they can refer to any instance of a class. 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 effect of the second statement is subtle. Remember that i is a value type and it exists in the stack. If the reference inside o referred directly to i, the reference would be referring to the stack. However, all references refer to objects on the heap. Instead, a piece of memory is allocated from the heap, an exact copy of the value inside i is stored in this piece of memory, and the reference inside o is pointed to the copy. (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.) This automatic copying of an item from the stack to the heap is called boxing. The following graphic shows the result:

Graphic
IMPORTANT
If you modify the original value of a variable, you are not modifying the value that now exists on the heap, because it's just a copy.

Previous Page
Next Page