Advertisement
Intermediate C#, Value vs Reference Types

What is boxing and unboxing, and why does it matter?

Short answer

Boxing wraps a value type in a heap object (implicit); unboxing extracts it (explicit cast). Both allocate/copy and hurt performance in loops.

Save C# mock interview
Advertisement
AModel answer
Boxing wraps a value type in a heap object (implicit); unboxing extracts it (explicit cast). Both allocate/copy and hurt performance in loops.
int n = 42;
object boxed = n;      // boxing
int back = (int)boxed; // unboxing
Real-world example
Non-generic ArrayList boxes every int; List<int> avoids it entirely.