posh.wiki


What actually is boxing, anyway?

2026-03-25

Tags: .NET

Boxing is a relatively niche feature of the .NET Common Language Runtime (CLR) that can be a powerful tool to increase performance and reduce memory usage if understood and used correctly.

Reference types vs value types

In .NET, there are two kinds of type.

Most classes are "reference" types. This means that you keep a pointer to the value instead of the value itself. If method A passes a reference type variable to method B and method B changes it, method A's copy of the variable will also reflect these changes. Reference types are allocated memory on the heap, meaning that they'll keep using memory until the garbage collector notices that there are no references left to it.

Most structs are "value" types. If method A passes a value typed variable to method B and method B changes it, method A's copy remains the same. Value types are allocated on the stack, and their memory is reclaimed immediately when they fall out of scope, which is significantly faster and less taxing on memory than reference types.

What is boxing?

Boxing is the term for when a value type is implicitly converted to a reference type, when it's assigned to a variable of type object or some interface that the value type implements. The value is copied, wrapped inside an object, and given a place on the heap.

int i = 5;
object o = i; // boxing happens here
IComparable c = i; // also here

Boxed values become reference types, so other methods can change them. If method A has object o, a boxed int, and passes it to method B, method B can change it. In this case, even though int is a value type, method A is aware of the change because the value has been boxed.

What is unboxing?

Unboxing is the explicit process of taking a boxed value type and turning it back into a value type.

object o = 123;
int i = (int)o;

The value in int i is no longer tied to object o, so if we change o, it won't be reflected in the value of i.

What are the implications of boxing?

Relative to normal assignments, boxing is computationally expensive. This difference is often negligible, except on low power hardware or at massive scale.

Boxing isn't inherently bad, but it should be used with care, since it can lead to easy-to-miss bugs. Similarly, unboxing should be done with care, since it might result in an InvalidCastException if the more derived type isn't what you expected.

To avoid it, prefer generic types (such as List<int> rather than ArrayList), and avoid writing APIs that take object as a parameter.