Monday 26 October 2015

Boxing and Unboxing


Boxing and unboxing is a  essential concept in .NET’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object.

Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation


class Test
{
                  static void Main() {
int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing
}
}


An int value can be converted to object and back again to int.

This example shows both boxing and unboxing. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box.

Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.



No comments:

Post a Comment