The boxing operation is accomplished by assigning the value – type variable to a variable of the type object:
int myInt = 123;
object myObj = myInt; //boxing
This means moving the value 123 from the stack to the heap, as shown the following figures.
Memory before boxing.
Memory after boxing.
In order to convert the variable back to a value type we use the unboxing operation, which is performed by casting the reference – type variable with (int). The following statement assigns the value pointed to by myObj to a new value-type variable, yourInt:
yourInt = (int) myObj; //unboxing
This statement creates a new value – type variable that contains the same value 123, as shown in figure: -
Memory after unboxing.
Notice that we can use the same variable, myInt, instead of using a third variable, yourInt, in the unboxing operation.
Boxing is necessary in cases when we would like to use value types in collections where items of the collection are of the type object. Unboxing is also used in accessing the value – type contents of an object.
Although the concept of reference – type variables is the same as pointers in C++, reference types save us the trouble of handling pointer operations, especially deleting the memory that was allocated to pointers. These operations are done for us in the background.
Tuesday, March 16, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment