What is boxing and unboxing?

Experience Level: Junior
Tags: .NET C# Performance

Answer

Explanation

  • Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.
  • Unboxing extracts the value type from the object.
  • Boxing is implicit
  • Unboxing is explicit.

Performance

In relation to simple assignments, 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.

Follow up questions

  • How does boxing and unboxing impact performance?
  • How to avoid the performance hit of boxing/unboxing?
  • What is the difference between stack and heap?
Related C# job interview questions