Advertisement
Intermediate C#, Value vs Reference Types

What is boxing and unboxing in C#, and why can excessive boxing hurt performance?

Short answer

Boxing converts a value type (like an int) into an object, copying the value onto the heap so it can be used anywhere a reference type/object is expected (such as in a non-generic collection); unboxing reverses this, extracting the value type back out of the boxed object via an…

Save C# mock interview
Advertisement
AModel answer
Boxing converts a value type (like an int) into an object, copying the value onto the heap so it can be used anywhere a reference type/object is expected (such as in a non-generic collection); unboxing reverses this, extracting the value type back out of the boxed object via an explicit cast, throwing InvalidCastException if the object doesn't actually contain the expected type -- both operations carry real overhead (an extra heap allocation for boxing, a cast check for unboxing), and doing this repeatedly (like storing many ints in an old-style ArrayList) generates unnecessary garbage collection pressure that generic collections avoid entirely.
int num = 10;
object boxed = num;        // boxing: copies 'num' onto the heap
int unboxed = (int)boxed;  // unboxing: extracts it back, with an explicit cast

// Avoids boxing entirely by using a generic collection instead of ArrayList
List<int> numbers = new() { 1, 2, 3 }; // ints stay as primitives, no boxing per element
Real-world example
A performance review of a legacy codebase using ArrayList to store thousands of integers finds that switching to the generic List<int> eliminates a boxing allocation on every single insertion, measurably reducing GC pauses under load.
Likely follow-ups
  • Why does the .NET small-integer cache concept (relevant in some other languages) not apply the same way to C# boxing?
  • What specific collection types should be preferred specifically to avoid boxing overhead?
Related topics