Boxing and UnBoxing Process in c#

C# Type System contains generally  two Types of data , they are Value Types , Reference Types.  Int, bool these are knows as value type and String, Class, Array are known as reference type.  C# allows us to convert a Value Type to a Reference Type, and back again to Value Types . The operation of Converting a Value Type to a Reference Type is known as Boxing and Reference type to value type is Known as Unboxing.


1:       int firstNumber = 1;

2:       Object Obj = firstNumber ; //Boxing,Obj is reference type here

The first line I created a Value Type firstNumber and assigned a value 1 to firstNumber. The second line , I created a variable of object type(Reference type) and assign firstNumber value to reference type  variable(Obj).  From the above operation we saw converting a firstNumber of a Value Type into a value of a corresponding Reference Type . This type of operation is called Boxing. It means conversion of value data type to Reference type (Object) is known as Boxing .


  1:          int firstNumber = 1;

  2:          Object Obj = firstNumber ; //Boxing

  3:          int returningNumber= (int)Obj; //Unboxing

The first two line shows how to Box a Value Type . The next line (int returningNumber= (int)Obj) shows extracts the Value Type from the Object type(reference type) . That is converting a value of a Reference Type into a returningNumber of a Value Type. This operation is known as UnBoxing.



Leave a Reply

Your email address will not be published. Required fields are marked *