skip to content

Boxing and Unboxing

Converting a value type to object or an interface allocates a box, and unboxing must name the exact type. Interviewers ask where boxing hides and how generics avoid it.

on this pageshow

explore

questions

5

In C#, what happens when an int is assigned to an object variable, and what does casting it back to int do?

level: juniorimportance: must knowfreq 80%

answer

  1. a heap object for a value
  2. what the variable actually holds
  3. the cast checks the type
  4. two boxes, two identities

basics

~20 s

Assigning an int to object boxes it: the runtime allocates a heap object and copies the value in. Casting back unboxes it: the runtime checks the box holds an int and copies the value out. Later changes to the local never reach the box.

solid answer

~40 s

Boxing is the implicit conversion from a value type to `object` (or to an interface the type implements). The runtime allocates a new object on the managed heap, copies the `int` into it and hands back a reference. The box is a snapshot: assigning a new value to the original local afterwards does not change it. Unboxing is the explicit cast `(int)o`; the runtime first checks that `o` really holds a boxed `int` (throwing `InvalidCastException` if it holds another type, `NullReferenceException` if `o` is null) and then copies the value out. Every boxing conversion creates a separate object, so two boxed 7s compare `false` with `==` on `object`, which compares references, and `true` with `Equals`, which compares the values.

code

csharp · 13 lines
csharp
int count = 42;
object boxed = count;      // boxing: a new heap object holding a copy of 42
count = 100;               // changes the local variable only

Console.WriteLine($"count = {count}, boxed = {boxed}");   // count = 100, boxed = 42

int back = (int)boxed;     // unboxing: check the box holds an int, then copy it out
Console.WriteLine(back);                                   // 42

object first = 7;
object second = 7;                                         // a second, separate box
Console.WriteLine(first == second);                        // False: == on object compares references
Console.WriteLine(first.Equals(second));                   // True: Int32.Equals compares the values

go deeper

for a junior

Recall the two steps: boxing allocates a heap object holding a copy, and unboxing checks the type and copies the value back out. Show that changing the original afterwards leaves the box untouched.

for a middle

Explain why == on two object variables compares references while Equals compares the boxed values, and name the places the compiler inserts a box for you: object parameters, object fields and interface variables.

for a senior

Connect boxing to allocation pressure: each box is a short-lived heap object, so boxing in a per-request or per-frame loop turns into garbage collections. Name the generic, typed alternative for each case.

for a principal

Treat an object-typed API for numbers as a cost every caller pays in allocations, and weigh one simple object signature against generic or strongly typed overloads that keep values unboxed.

## Value types, reference types and `object` C# has two families of types. A **value type** (`int`, `double`, `bool`, `DateTime`, any `struct` or `enum`) holds its data directly: a local of type `int` *is* the four bytes of the number. A **reference type** (`string`, `object`, any `class`, any interface) is a reference to an object that lives on the **managed heap**. Yet every type, `int` included, derives from `System.Object`, so a C# program can treat any value as an `object`. **Boxing** is the mechanism that makes that possible for value types. ## What boxing does `object boxed = count;` compiles without a cast because boxing is an **implicit** conversion. At run time it performs these steps: 1. Allocate a new object on the managed heap, large enough for an object header, a pointer to the type's method table and the value itself (24 bytes for an `int` on a 64-bit .NET 10 process). 2. Copy the current value of `count` into that object. 3. Return a reference to the new object, which is what `boxed` now holds. The same happens when a value type is converted to an **interface** it implements, for example `IComparable<int> c = count;`, because an interface type is a reference type too. ## What unboxing does Getting the value back needs an **explicit** cast, `(int)boxed`. Unboxing runs two steps: 1. **Check** that the reference points at a boxed value of exactly the target type. A box of another type throws `InvalidCastException`; a null reference throws `NullReferenceException`. 2. **Copy** the value out of the box into the target variable. Unboxing does not allocate. Its cost is the type check and the copy, which Microsoft's documentation describes as expensive to a lesser degree than boxing. ## The box is a copy Because step 2 of boxing copies the value, the box and the original variable are independent from that moment on: ```csharp int count = 42; object boxed = count; // box holds 42 count = 100; // only the local changes Console.WriteLine(boxed); // 42 ``` Nothing links `boxed` back to `count`. The same is true in the other direction: the value you unbox is a fresh copy, and changing it does not touch the box. ## Every box is a new object Each boxing conversion allocates its own object, even for equal values. That matters as soon as code compares two `object` variables: | Expression | Result | Why | |---|---|---| | `first == second` (both `object`, both boxed 7) | `false` | `==` on `object` compares references, and these are two boxes | | `first.Equals(second)` | `true` | the virtual call reaches `Int32.Equals`, which compares the values | | `(int)first == (int)second` | `true` | both sides are unboxed to `int` first | .NET keeps no cache of boxed integers, so there is no range of small numbers for which two boxes happen to be the same object. Equality rules in general are covered with equality and hashing; the point here is only that a box has an identity of its own. ## Why it matters - **Allocation.** Every box is a heap object the garbage collector must later reclaim. One box is cheap; a box per item per request or per frame is steady garbage. - **Hidden conversions.** No syntax marks a boxing conversion. Passing an `int` to a parameter of type `object`, storing it in an `object` field, adding it to a non-generic collection or assigning it to an interface variable all box silently. - **Copies diverge.** Code that boxes a value and keeps using both the box and the original is working with two copies. - **Generics avoid it.** `List<int>` stores `int` values directly in an `int[]`, while the older `ArrayList` stores `object` references and so boxes every element it is given. ## Spotting a box in everyday code Boxes a beginner writes without noticing: - `Console.WriteLine("{0} items", count)`: the composite-format overloads take `object?` arguments. - `var bag = new ArrayList { count };`: every element of `ArrayList` is an `object`. - `object setting = 30;` in a settings class with `object`-typed properties. - `IComparable<int> c = count;`: an interface variable holding a value type. A good habit is to ask, whenever a value type meets a parameter, field or collection typed `object` or an interface: is a box being made here, and does the code need it?

  • If int derives from object, why does calling ToString() on a plain int local not box it?
    `int` is an alias for the struct `System.Int32`, which overrides `ToString`. When a struct overrides the method, the call runs the struct's own implementation directly on the variable, so no box is needed. Boxing happens when the value has to become an `object` or interface reference: an `object` parameter or field, an interface variable, or a call to a method the struct only inherits from `ValueType`.
  • Does unboxing allocate memory the way boxing does?
    No. Unboxing checks the box's type and copies the value out into the target variable; nothing new is created on the heap. In a box-and-unbox round trip the only allocation is the box itself. Unboxing still costs the type check and the copy, so it is cheaper than boxing but not free.

Boxing is like photocopying a form and sealing the copy in a labelled envelope: anyone who accepts any envelope can carry it, but editing your original form later changes nothing inside, and the envelope opens only for someone asking for exactly that form.

  • The object variable points at the original int local, so later changes show up in both.
  • Boxing is free because an int already is an object.
  • Two boxed 7s are equal with == on object because the values match.
  • Unboxing allocates a new int on the heap.
  • Boxing only happens when you write an explicit (object) cast.
open as a page

In C#, why does `long total = (long)value;` throw InvalidCastException when the `object value` holds a boxed int?

level: middleimportance: must knowfreq 60%

basics

~20 s

Casting object to long is an unboxing conversion, and unboxing succeeds only for the exact value type that was boxed. The box holds an Int32, so the runtime throws InvalidCastException; unbox to int first, then widen: (long)(int)value.

open as a page

In C#, a mutable Counter struct is assigned to an IIncrement interface variable; why does calling Increment through that variable leave the struct unchanged?

level: middleimportance: should knowfreq 45%

basics

~20 s

Converting a struct to an interface type boxes it, so the interface variable refers to a heap copy. Increment mutates that boxed copy; the original local never changes, and casting the box back to Counter yields yet another copy.

open as a page

In C#, why does a generic method constrained with `where T : IComparable<T>` call CompareTo on an int without boxing, while an `IComparable<int>` parameter boxes it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Inside the generic method the compiler emits a constrained call on the T value itself, and for an int the JIT turns it into a direct call to Int32.CompareTo. An IComparable<int> parameter is a reference, so the int must be boxed to pass it.

open as a page

An allocation profile of a C# service shows Int32 boxes from a metrics logger with object parameters and a legacy ArrayList; where else does boxing hide, and how do you remove it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Boxing hides wherever a value type meets an object or interface signature: ArrayList and Hashtable, object parameters, string.Format arguments, and ToString or GetHashCode on a struct that does not override them. Generic, typed APIs remove it.

open as a page