C# boxing and unboxing: what it is and why it hurts performance

C# Language Interview Q&A November 13, 2026 csharp

Converting a value type to object (or an interface): a copy is created on the heap.

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ======================================================================
// Q: What is boxing? Why does it matter?
//
// Converting a value type to object (or an interface): a copy is created on the
// heap. Unboxing is the reverse, with a type check. It costs allocations and GC
// on hot paths. Avoid it with generics (List<int> instead of ArrayList) and by
// not using object parameters.
// ======================================================================

int n = 42;
object o = n;          // boxing: allocation on the heap
int m = (int)o;        // unboxing
var list = new List<int> { n };   // no boxing: generic