Understanding Boxing & Unboxing Day 22
Boxing is used to store value types in the garbage-collected heap.
Boxing is an implicit conversion of a value type to the type
object
or to any interface type implemented by this value type.Boxing a value type allocates an object instance on the heap and copies the value into the new object.
Consider the following declaration of a value-type variable :
The following statement implicitly applies the boxing operation on the variable i :
The result of this statement is creating an object reference o, on the stack, that references a value of the type int , on the heap.
This value is a copy of the value-type value assigned to the variable i.
The difference between the two variables, i and o, is illustrated in the following image of boxing conversion :
It is also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required :
This example converts an integer variable i to an object o by using boxing.
Then, the value stored in the variable i is changed.
Unboxing is an explicit conversion from the type object of a value type or from an interface type to a value type that implements the interface.
An unboxing operation consists of :
The following statements demonstrate both boxing and unboxing operations :
The following figure demonstrates the result of the previous statements :
For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type.
Performance Profile :
Comments
Post a Comment