What is boxing and unboxing in C#, and why is it a performance concern?
cs-jun-005
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
Boxing wraps a value type in a heap-allocated object so it can be treated as a reference type. Unboxing extracts the value back. Both require a heap allocation and a copy, which is significantly slower than stack operations. The most common source of accidental boxing is storing value types in non-generic collections (ArrayList, Hashtable) or passing an int where object is expected. With generic collections — List<int>, Dictionary<int, T> — the compiler avoids boxing entirely. For high-throughput hot paths, even a few hundred thousand boxing allocations per second will pressure the GC.
Code example
int x = 42;
object boxed = x; // boxing: heap allocation
int y = (int)boxed; // unboxing: copy back to stack
// Avoid boxing with generics
var badList = new System.Collections.ArrayList();
badList.Add(42); // boxes!
var goodList = new List<int>();
goodList.Add(42); // no boxing
// String.Format boxes — use string interpolation or StringBuilder
string s1 = string.Format("value: {0}", 42); // boxes 42
string s2 = $"value: {42}"; // no boxing
Follow-up
How does struct layout (sequential vs auto packing) affect P/Invoke marshalling? How does Nullable<T> avoid boxing compared to casting to object?