What is boxing and unboxing in c#?

In c# type system are mainly of 3 types

  • Value type
  • Reference type
  • Pointer type

BOXING

The operation of converting a value type to  reference type is called BOXING

	int Val = 1;
 	Object Obj = Val; //Boxing
  • The first line we created a Value Type Val and assigned a value to Val
  • The second line , we created an instance of Object Obj and assign the value of Val to Obj.

From the above operation (Object Obj = i ) 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

The operation of converting a   reference type to  value type  is called UNBOXING

 	int Val = 1;
 	Object Obj = Val; //Boxing
 	int i = (int)Obj; //Unboxing
  • The first two line shows how to Box a Value Type .
  • The third line (int i = (int) Obj)  means extracting the value type from object
  • It means  converting value of a reference  type into a value of a Value type

This  operation is called Unboxing.

Leave a Reply