Boxing and Unboxing in C#

Boxing - Boxing is required in situation when a value type is converted in to a base object or on interface. The CLR(common language run time) converts the value type to reference type.Boxing is an expensive process, since it copies an object from a stack to a heap which requires a number of processor as well as space on the heap.
 
 Another disadvantage of using boxing is that the same object appears at two different places in memory which can have contradictory state.
 
 Example
 
 int a=10;
 object b=a;
 
 Unboxing - unboxing is a process of converting an instance of object type or interface back to value type. Type casting is must in the case of unboxing,this is done explicitly by using unboxing.
 
 Example
 

 int a=10;
 object b=a;
 int c=(int)b;
 
 Note - We can unbox a variable that has been previously boxed.
Ebook Download
View all
Learn
View all