Difference between Boxing & Unboxing in C#
Generally if variable moves from stack to heap that is known as Boxing and if variable moves from heap to stack that is known as Unboxing . So we can also say it as the process of converting .NET data types from value types to reference types is known as Boxing and vice-versa process is known as Unboxing . Boxing and Unboxing are normally a bad process which also make our system slower because here we are changing the memory addresses. But there are some condition where that is necessary to do the Boxing/Unboxing like taking data from UI or binding data to grid. But unnecessary doing boxing and unboxing is very bad practice.
Boxing is an implicit conversion process and Unboxing is an explicit conversion process let we discuss both through an example :
As we discussed above, it is the process of converting value type to reference type.
Here initially we assign integer data type x=22 which is stand alone primitive data type so we can simply call it as value type and the in another line we should copying that value on object obj1 which means it should be now converted it into reference type. We are copying the value and put it into object which holds memory address so object can put it into heap from stack.
As we already discussed in above it is the process of converting reference type to value type.
Here we are converting the object obj1 to integer x. We are just converting the reference type to value type means firstly, obj1 should holds the reference of the of obj1 that means hold the memory address rather than holing value now when it converted to integer it can directly hold that value what actual object should hold. Now memory address should be changed from heap to stack. lets see it on add watch:
This is all about boxing and unboxing concepts.
For very detailed understanding check out below video on Boxing VS Unboxing and some other related concepts