Advertisement
Intermediate C# Programming, Data Types in C#

What happens during the process of boxing?

Short answer

During boxing, the runtime allocates a new block of memory on the heap, copies the value type's data into that newly allocated memory, and wraps it inside an object reference, meaning the original stack based value type and the new heap based boxed object become two completely…

Save C# Programming mock interview
Advertisement
AModel answer
During boxing, the runtime allocates a new block of memory on the heap, copies the value type's data into that newly allocated memory, and wraps it inside an object reference, meaning the original stack based value type and the new heap based boxed object become two completely separate pieces of memory holding a copy of the same value. This copy step is exactly why changes made to the boxed object do not affect the original value type variable, and vice versa.
int original = 5;
object boxed = original;  // heap allocation happens here, a copy of 5 is stored
original = 10;
Console.WriteLine(boxed); // still prints 5, because boxed holds a separate copy
Real-world example
A performance sensitive application processing millions of numeric values in a loop avoids storing them in a non generic ArrayList, which would box every single value, and instead uses a generic List<int> to avoid the repeated heap allocations entirely.
Likely follow-ups
  • Why do generic collections like List<T> avoid the boxing overhead that non generic collections like ArrayList have?
  • Is there a way to check how much boxing is occurring in an application?
Related topics