Glossary / Boxing and unboxing

Boxing and unboxing

Boxing converts a value type to object, ValueType, or an implemented interface representation; unboxing converts that boxed object back to the exact value type. Boxing bridges value types with APIs expecting reference types, but can allocate and copy data, so repeated boxing in hot paths may affect performance.

Semantics and failure cases

int number = 42;
object boxed = number;       // boxes a copy
number = 7;
int restored = (int)boxed;   // 42

The boxed value is a separate representation; changing the original variable does not update it. Unboxing requires the boxed runtime value to have the exact expected value type (or compatible nullable rules); casting to a different numeric type does not perform numeric conversion and throws InvalidCastException. Unboxing null to a non-nullable value type throws NullReferenceException.

Converting a struct to an interface can box it. Generic methods constrained to a struct or interface can often avoid boxing through constrained calls, depending on code and runtime. Modern JIT optimizations and newer APIs can eliminate some allocations, but inspect generated code/allocation profiles rather than assuming.

Engineering guidance

Use generic collections and APIs rather than non-generic object-based paths. Avoid value-type interface conversions in allocation-sensitive loops unless measured. Use typed parsing/conversion APIs for numeric changes; unboxing is not numeric conversion. Benchmark realistic workloads and allocation rates.

Interview questions

  1. Does boxing preserve a live link to the original struct? No; it stores a boxed copy.
  2. Can you unbox boxed int as long? No; that is a different runtime type and fails.
  3. Where might boxing occur? Object/interface parameters, non-generic collections, formatting/logging APIs, and some unconstrained generic paths.
  4. Does generic code always box structs? No; constrained generic calls can avoid boxing, but inspect actual pattern/runtime.
  5. How detect impact? Allocation profiling and benchmarks.

References