Boxing and unboxing are important concepts in C#. Here we willlearn how to use and benifits of Boxing and Unboxing in C#.
C# allows us to convert a Value Type(char, int etc.) to a Reference Type(object) process is called Boxing . Value Type variables are always stored in Stack memory.
Example
int num = 10;
Object Obj = num; //Boxing
The first line we created a Value Type num and assigned a value to num. The second line , we created an instance of Object Obj and assign the value of num to Obj. From the above operation (Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type. These types of operation is called Boxing.
C# allows us to convert a Reference Type(object) to a Value Type(char, int etc.) is called UnBoxing . Reference Type variables are stored in Heap memory.
Example
int num = 10;
Object Obj = num; //Boxing
int i = (int)Obj; //Unboxing
The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows extracts the Value Type from the Object. That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.
To store value types in collections or pass them as object parameters: In C#, collections such as ArrayList and Dictionary require objects as elements, so value types must be boxed to be stored in these collections. Similarly, when passing a value type to a method that takes an object parameter, the value type must be boxed.
However, it is important to note that there are also some drawbacks to using boxing and unboxing. These include: