Boxing and UnBoxing using System.Object in C#

 

In .Net we have two groups of data types; those are value types and reference types. The example of value types are int, short…etc and example of reference types are Object, Class…..etc. Value type fields stored in Stack memory and reference type fields stored in Heap memory.

 

Sometimes we may have requirement like converting one group of data types to another group of data types to manage the memory of the fields.

 

In C#, converting value type variables to reference type is called Boxing and in-reverse converting that reference type to specific value type is called UnBoxing.

 

For example we have some value type variable “iNumber” of int type. The variable “iNumber” stores in stack memory because it is Value type, but whenever we want to force CLR to manage the memory we have to store the value type variables like reference type variables that means in heap memory. For that we have to convert the int type variable to Object type which is reference type as shown below.

 

            int iNumber = 10;

            object obj = iNumber;//convert the int type to object

 

As shown above the value 10 is stored in heap memory and only reference is stored in obj variable.

Whenever we want to get the actual value we have to use UnBoxing technique. Convert the object type to int type as shown below which is called UnBoxing.

 

            int iNumber = 10;

            object obj = iNumber;//convert the int type to object

 

            int iNumber1 = (int)obj;//convert the object type to int type

 

Advantage of Boxing & UnBoxing techniques:

In C#, value types are stored in stack memory and reference types are stored in heap memory. Memory allocation in stack memory has to handle by developers whereas memory allocation in heap memory is handled by CLR. So whenever you want force CLR to handle value type variables use Boxing technique and to get the value back from reference type use UnBoxing technique.