Boxing and Unboxing in C#

Introduction to Boxing and Unboxing

As we know that one of the strongly-typed language is C#. It allows users to convert value types into reference types. One can easily convert the value of any value type into some reference type, this conversion from value type to reference type is known as boxing and unboxing is converting from reference type to value type. Boxing is known as implicit conversion, whereas unboxing is known as explicit conversion. Boxing and unboxing are very important concepts in C#.

Boxing and Unboxing in C#
Boxing and Unboxing in C#


While Boxing C# uses implicit conversion, for example, when we want to box two different value types i.e. int or char into a reference type of object. The compiler checks the value type it place the value into an object box. As all the value types are derived from object. First of all these values are stored in the Stack and after that they move into the heap memory, for holding these values C# creates a box of type object for holding values into the memory.


Create any number of values of different value types.

Create same number of objects for the values and save the variables in the objects.



While unboxing C# used explicit conversion, For example, when we want to unbox any value from some object, the only thing we need to know is the value type of the data to be unboxed. In this conversion we move the data from the heap to stack memory, i.e. conversion from interface-type to value type. Then they are assigned to basic value type.

To get the values from objects you need to specify the initial value type of the value.

If you give a wrong value type it will throw InvalidCastException.

You can save these values in any new variable of same value type.

You can display these variables through the new variables as well as you can directly print out these values.

Complete Example of Boxing and unboxing

ArrayList also implements the concept of boxing and unboxing