Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Types and Literals

Boxing and unboxing

Reference for C# boxing and unboxing: converting value types to object or interfaces, the allocation cost, InvalidCastException, mutation traps and how to avoid it.

Boxing is the conversion of a value type (such as int, a struct or an enum) to object, System.ValueType or an interface it implements. The runtime allocates an object on the heap and copies the value into it. Unboxing is the explicit conversion back, which checks the type and copies the value out.

Boxing is invisible in the source, which is why it is a classic hidden cost. Each boxing is a heap allocation that the garbage collector must later reclaim, and an unboxing needs an exact type match.

C#
int n = 42;
object box = n;        // boxing: allocates
int back = (int)box;   // unboxing: type check + copy

Try it

C# Boxing copies the value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Hidden boxing and mutable structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
object o = valueTypeInstance;          // boxing (implicit)
IFoo f   = structImplementingIFoo;     // boxing to an interface (implicit)
T value  = (T)o;                       // unboxing (explicit, exact type)
int? maybe = o as int?;                // unbox to nullable without exception
if (o is int i) { }                    // pattern-based unboxing
Operation Result
Box New heap object holding a copy of the value, with a method table pointer. Roughly 16 bytes of overhead on 64-bit for a small value.
Unbox Checks that the object is a box of exactly the target type (or its nullable form), then copies the value.
Box a nullable int? with a value boxes as a plain int; int? without a value boxes as null.

Errors. Unboxing a null reference to a non-nullable value type throws NullReferenceException; unboxing to the wrong type throws InvalidCastException.

Usage notes

  • Boxing is a copy. The box and the original are independent. Mutating the original after boxing does not affect the box.
  • Mutating through an interface changes the box, not your variable. This is the most common surprise with mutable structs; make structs readonly to avoid it.
  • Where hidden boxing occurs: object parameters (Console.WriteLine(string, object) overloads, string.Format), non-generic collections (ArrayList, Hashtable), calling an inherited ToString, Equals or GetHashCode on a struct that does not override them and assigning a struct to an interface variable.
  • How to avoid it. Use generics (List<T>, Dictionary<K,V>), generic constraints (where T : IFoo) which the JIT specializes for structs, override ToString/Equals/GetHashCode on your structs, implement IEquatable<T>, and use ReadOnlySpan<T> or stackalloc instead of arrays of object.
  • Nullable special rule. Nullable<T> has no box of its own; the runtime unwraps it, so object o = (int?)5 holds a boxed int.
  • Performance. One boxing costs an allocation of 24 bytes or so for an int and later GC work. In a hot loop it adds up; measure with a benchmark or allocation profiler rather than guessing.
  • Enums box too, like every other value type.