CKTIS / C#
Boxing and unboxing values in C#
Learn when C# copies a value into an object, why the boxed type must match when unboxing, and which exception each kind of failure produces.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
object boxed = value; // value has a boxable value type T
T copy = (T)boxed; // T is the original non-nullable value type
T? optional = (T?)boxed; // also accepts null and yields an empty T?Boxing/unboxing are conversions between value types and reference types. Boxing implicitly converts a value such as an int to object or to an interface type it implements. The runtime normally allocates an object on the managed heap to hold a copy of the value. Changing the original variable doesn't change that copy. Frequent boxing can increase garbage collection pressure; List<int> stores elements without boxing them.
Unboxing is an explicit conversion that checks the boxed type and copies the value out. The C# rule for a non-nullable value-type target is an exact type match. If boxed contains an int, (int)boxed succeeds, but (long)boxed throws InvalidCastException even if the number fits in a long. In long widened = (int)boxed;, the cast first unboxes the int, and the assignment then implicitly converts it to long.
Unboxing a null reference to a non-nullable type such as int throws NullReferenceException. A non-null reference that doesn't point to a compatible object causes InvalidCastException instead.
Boxing T? is different: if HasValue is true, the underlying T is boxed, not the T? instance; otherwise the result is a null reference and no object is allocated. Unboxing to T? gives an empty value for null or a value containing T for a boxed T. An incompatible object still causes InvalidCastException.
Examples
#nullable enable
using System;
int source = 42;
object boxed = source;
source = 7;
Console.WriteLine(FormattableString.Invariant($"source={source}; boxed={(int)boxed}"));
long widened = (int)boxed;
Console.WriteLine(FormattableString.Invariant($"widened={widened}"));
try
{
_ = (long)boxed;
}
catch (InvalidCastException)
{
Console.WriteLine(nameof(InvalidCastException));
}
object? empty = (int?)null;
try
{
_ = (int)empty!;
}
catch (NullReferenceException)
{
Console.WriteLine(nameof(NullReferenceException));
}
int? present = (int?)boxed;
int? absent = (int?)empty;
Console.WriteLine(FormattableString.Invariant($"nullable value={present}; empty HasValue={absent.HasValue}"));Result
source=7; boxed=42 widened=42 InvalidCastException NullReferenceException nullable value=42; empty HasValue=False
Changing `source` to `7` leaves the boxed `42` unchanged. The `!` in `empty!` only suppresses the compiler's possible-null warning; it doesn't change the value or prevent the exception.
Related lessons
- C# · Lesson 37 · Intermediate · Version: 2