Boxing and unboxing are processes of converting value types to object type or from object type to a value type. During boxing value type is taken and converted to object type, while during unboxing object type is converted to explicitly defined type, so we can say that Boxing is implicit and unboxing is explicit.

Let’s look at boxing through example:

We have a job to convert two numbers to an object type. Usually we assign numbers to an integer type. Int type can hold numeric values from -2,147,483,648 to 2,147,483,647, but Int64 can hold larger numeric values from -9223372036854775808 to 9223372036854775807. So our job is to convert numbers 2,147,483,000 and 3,147,483,800 to an object. We can do it simply by writing following code:

What we essential did was that we created two variables one int variable to hold number 2147483000 and Int64 variable because number is to large to be stored inside int variable. Then we took those two variables and assigned them to an object type variables.

Unboxing is an opposite process of boxing. First we will take a few object variables with different types of values, like string, int and double and convert them to a desired type by casting. Casting is specifying type in round brackets before objects variable. Let’s take a look:

There are a few things you should always consider while boxing or unboxing.

  • Both boxing and unboxing are expensive operations. While boxing a new object must be created on a managed heap. While unboxing does not usually require creating allocation of a new memory it is still a expensive operation.
  • You can unbox object to a lot of different value types. For example, you can unbox numeric value 5 to a int or a string if you wish:

  • List of objects is also possible

  • Beware of InvalidCastException exceptions that occur when unboxing incorectly