Sunday, June 16, 2013

Boxing and Unboxing in C#

Boxing

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 of a value allocated an object instance and copies the values into the new object.
Consider the following declaration of a value-type variable:

int i = 123;
The following statement implicitly applies the boxing operation on the variables:
Object o = i;

The result of this statement is creating an object, 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 0 is illustrated in the following figure.
Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type.
It also possible, but never needed to perform the boxing explicitly as in the following example

Int i = 123;
Object O = (object) i;

Unboxing

Unboxing is an explicit conversion from the object to value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
• Checking the object instance to make sure it is a boxed value of the given value type.
• Copying the value from the instance into the value-type variable.

The following statements demonstrate both boxing and unboxing operations:
Int i = 123;       // a value type
Object O = i;   //boxing
int j = (int) O;   // unboxing

Unboxing is an explicit conversion from the object to value type or from an interface type to a value type that implements the interface.

For the unboxing of value types to succeed at runtime, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null or a reference to an incompatible value type will return an invaIidcastException.

No comments:

Post a Comment