Boxing and Unboxing

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

Boxing Conversion

BoxingConversion graphic

explicit boxing is never required:

Unboxing is an explicit conversion from the type object to a 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 that it is a boxed value of the given value type.

—Copying the value from the instance into the value-type variable.

Unboxing Conversion

UnBoxing Conversion graphic

unboxing of value types to succeed at run time

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing

Leave a Reply