Skip to content
Codescope

Boxing & unboxing

Assigning an int to an object allocates. The syntax gives no hint that it happened.

core8 min7 steps

Before you start

In C#, an int is a value type. But object is a reference type. So what happens when you assign an int to an object variable? The runtime wraps the int in a heap-allocated box — this is **boxing**.

It's easy to miss. object o = 42 looks free. It isn't — that one line allocates a small heap object, copies the 42 into it, and stores a reference. Do this in a tight loop and you've made a real problem.

This lesson watches an int get boxed on assignment, unboxed back on cast, and shows why generics (List<int>) exist to avoid this whole dance.

Stack

Main()
iint
42

Every struct in C# starts out like this: the value, in place.

Step 1 of 7. An int is 4 bytes in place. `int i = 42` stores the number directly in the local's slot. No allocation, no header, no indirection. That is the whole point of a value type — and exactly what gets lost in the next line.

01 / 07

Step 01 / 07

An int is 4 bytes in place

int i = 42 stores the number directly in the local's slot. No allocation, no header, no indirection.

That is the whole point of a value type — and exactly what gets lost in the next line.

Program.csC#
int i = 42;object boxed = i;        // box: copy onto the heapint back = (int)boxed;   // unbox: copy back, with a type checki = 7;                   // the box still holds 42var list = new ArrayList();list.Add(1);             // boxes every elementvar typed = new List<int>();typed.Add(1);            // no boxing — generics keep it a valueobject o = "text";int bad = (int)o;        // InvalidCastException