C# Boxing and Unboxing

When the CLR boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap.

Boxing is implicit; Unboxing is explicit.

Permormance

Boxing and Unboxing are computationally expensive processes.

When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

Boxing

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

Boxing is used to store value types in the garbage-collected heap. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Unboxing

Unboxing extracts the value type from the object.

Boxing and Unboxing Example

The following statements demonstrate both boxing and unboxing operations:

The integer variable i is boxed and assigned to object o.

o is unboxed explicitly and assigned to the integer variable j.

Invalid Unboxing Example

Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

Attempting to unbox null causes a NullReferenceException.

Leave a Reply