Boxing and unboxing

Storing a value type in an object variable wraps a copy of it in a heap object. Reading it back copies it out again.

Time O(1) plus an allocationSpace heapCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

object is a reference type, so it cannot hold an int directly. The runtime allocates a small object, copies the int into it, and stores the reference. The box is a snapshot, not a link to the original variable.

Code

int n = 42;
object o = n;          // boxing: copy the value into a heap object
n = 7;
int m = (int)o;        // unboxing: copy the value back out
Console.WriteLine(n + " " + m);   // 7 42

Tips

In the .NET library

Generics exist largely to avoid this. List<int> stores ints directly, while the old ArrayList boxed every element.