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.
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 42Tips
- Boxing allocates memory and unboxing needs a type check, so doing it in a hot loop is slow.
- Unboxing to the wrong type, such as (long)o here, throws InvalidCastException.
In the .NET library
Generics exist largely to avoid this. List<int> stores ints directly, while the old ArrayList boxed every element.