lunes, 22 de septiembre de 2014

Boxing & Unboxing in C#


The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

Boxing Conversion

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.

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 is implicit

// Boxing copies the value of i into object o.
object o = i;

int i = 123;
object o = (object)i;  // explicit boxing



Unboxing Conversion 

Unboxing extracts the value type from the object.

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 is explicit.

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


source: msdn.microsoft.com