Difference Between Boxing and Unboxing in C#

Boxing is a procedure of converting a value type to an object type. Here, the value type is stored on the stack and the object type is stored in the heap memory.

Let’s understand Boxing with an example :
int i = 24;
object ob = i; // Box the integer type n into object type ob.

In above code, the integer type i containing value 24 is stored on the stack and is copied to the object type ob. An object type is now referring to an integer value.  Now the “int i” also contain value 24 and the “object type ob” also contain value 24, but both the values are independent of each other i.e. if you change the value of i, it won’t reflect the change in the value of ob.



Unboxing is a conversion of the object type to the value type. In Unboxing the value of boxed object type stored on the heap is transferred to the value type that is stored on the stack. Unlike Boxing, the Unboxing has to be done explicitly. The object type is explicitly cast to the value type, and the value type must be same as value the object type is referring to.

Let’s understand Unboxing with an example :
int i = 24;
object ob = i; // Box the integer type n into object type ob.
int j = (int) ob; // Unbox the integer value stored in object type ob to integer type y.