DEV Community

Cover image for Boxing and Unboxing in C#
Theodore Karropoulos
Theodore Karropoulos

Posted on

Boxing and Unboxing in C#

What boxing is?

As Microsoft's documentation explains, boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. In simple words boxing is the process of converting a value type to reference type. When boxing take place the CLR it wraps the value inside a System.Object instance and stores it on the managed heap. Boxing is implicit conversion process.

Example

int num = 22;
object _object = num;
Enter fullscreen mode Exit fullscreen mode

Unboxing

Unboxing as you can already imagine is the exact opposite process, meaning the process of converting a reference type to value type. Unboxing is an explicit conversion process and a to step operation. First it checks the object instance to make sure that it is a boxed value of the given value type and then copies the value from the instance into the value type variable.

Example

int num = 22;
object _object = num; // Boxing
int _int = (int)_object; // Unboxing
Enter fullscreen mode Exit fullscreen mode

What about performance

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be created and allocated into memory. Likewise the cast required for unboxing is also expensive process and can take four times as long as an assignment.

Top comments (0)