Boxing and Unboxing in C#
Theodore Karropoulos

Theodore Karropoulos @tkarropoulos

About: Hello I am Theodoros, am a Software engineer with passion on new technologies, basketball and sports in general!

Location:
Greece
Joined:
Aug 4, 2020

Boxing and Unboxing in C#

Publish Date: Oct 9 '21
3 0

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.

Comments 0 total

    Add comment