C# › Memory & Garbage Collection

What is boxing and unboxing, and why does it have a real performance cost?

Intermediate

Answer

Boxing converts a VALUE TYPE into a reference-type object (wrapping it in a heap-allocated box) implicitly whenever a value type is used where 'object' (or an interface) is expected; unboxing converts it back. Both involve a HEAP ALLOCATION (for boxing) and a COPY operation, which is measurably slower than working with the value type directly, especially in tight loops.
int number = 42;
object boxed = number;        // boxing: heap allocation, copies the int into a new object
int unboxed = (int)boxed;     // unboxing: copies the value back out

// Generics avoid this entirely:
List<int> numbers = new();    // no boxing -- List<int> stores actual ints, not boxed objects
Real-world example Understanding why using a non-generic ArrayList (which stores everything as 'object') is significantly slower than a generic List<int> for value types.

Common follow-ups: How do generics specifically eliminate the need for boxing in scenarios where non-generic collections would require it?