Boxing and UnBoxing in C#.net

C# provides us with value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Value Type
Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32,double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types
Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.

Boxing Example


  int x = 5;
object Obj = x; // boxing

The first line we created a Value Type x and assigned a value to x. The second line , we created an instance of Object Obj and assign the value of x to Obj. The above operation (object Obj = x ) we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.

UnBoxing Example

  int y = (int)Obj; // unboxing

The first line (int y= (int) Obj) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.