Boxing And Unboxing Explained In C#

Introduction 

 
In this blog, I will explain boxing and unboxing in C#, which introduces two methods. Boxing and unboxing are both conversion types. Boxing is implicitly conversion and unboxing is explicitly a conversion type. The basic difference between boxing and unboxing is that boxing is the conversion of the value type to an object type, whereas unboxing refers to the conversion of the object type to value type.
 

Boxing

  1. Boxing refers to the conversion of the value type to object type.
  2. It is implicitly conversion.
  3. The value is stored on the stack memory and copied to the object stored on heap memory.
Example
  1. public class Sample  
  2.    {  
  3.       static void Main()  
  4.       {  
  5.          int i = 20;  
  6.          object obj = i;  
  7.       }  
  8.   
  9. }  

Unboxing

  1. Unboxing refers to the conversion of the object type to value type.
  2. It is explicitly conversion.
  3. The object value stored on the heap memory is copied to the value type stored on stack memory.
Example
  1. public class Sample  
  2.    {  
  3.    static void Main()  
  4.    {  
  5.       object obj = 20;  
  6.       int i = (int)obj;  
  7.    }  
  8.   
  9. }