Boxing and Unboxing in C#
Boxing is the way to convert a value type to the type object or to any interface type implemented by this value type. Simply we can can say that convert value type to reference type. When boxing is in process CLR boxes a value type and wrap the value inside a System.Object. It is an implicit conversion.
Example :
int var = 12; >> declare integer variable which is value type
object objVar=var ; >> declare object type and assign value type variable in to that
This is Boxing in which implicitly value type convert into object type.
Real example :
int var=7;
ArrayList arrlst = new ArrayList();
arrlst.Add(var) >> Boxing occurs
Above example ArrayList contains object type so when when we add var into arrlst Boxing occurs.
Unboxing is the same opposite of boxing, it converts the type object to the value type or we can say convert reference type to value type.Unboxing is an explicit conversion from the object type to the value type or an interface type to the value type.
An unboxing operation consists of:
- Checking the object instance to make sure that it is a boxed value of the given value type.
- Copying the value from the instance into the value-type variable.
Example :
int i = 123; >> a value type
object o = i; >> boxing
int j = (int)o; >> unboxing
Real example :
int var=7;
ArrayList arrlst = new ArrayList();
arrlst.Add(var)
int conVar=(int)arrlst[0]; >> unboxing occurs
Now I hope that we understand what is Boxing & Unboxing now we discuss what CLR act when these action perform:
Actually Boxing & unboxing relay on memory allocation by CLR. CLR allocate two types of memory
- STACK
- HEAP
When Boxing occurs in this process CLR convert Stack type to Heap type and in Unboxing CLR convert Heap type to Stack type.
Boxing Memory Example:
Unboxing Memory Example:
Boxing & Unboxing Example: