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, no sign-in needed to watch.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 42public class Main {
public static void main(String[] args) {
int n = 42;
Object o = n; // autoboxing: copy the value into an Integer on the heap
n = 7;
int m = (Integer) o; // unboxing: copy the value back out
System.out.println(n + " " + m); // 7 42
}
}int main() {
int n = 42;
any o = n; // C++ has no boxing: std::any copies the value into a type-erased holder
n = 7;
int m = any_cast<int>(o); // copy the value back out
cout << n << " " << m << "\n"; // 7 42
}n = 42
o: object = n # no boxing step: every Python int is already a heap object
n = 7 # rebinds n to a new object; o still refers to 42
m = int(o) # no unboxing either: o already is an int
print(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.