In C#, what does boxing an `int?` produce when it is empty and when it holds 42, and why does `GetType()` never report `Nullable<int>`?
answer
- the runtime special-cases the box
- empty becomes a null reference
- the box holds the payload type
- GetType is not overridden
basics
~10 sBoxing an empty int? produces a null reference; boxing one that holds 42 boxes the plain int. No boxed Nullable<int> ever exists, so GetType() reports System.Int32, or throws NullReferenceException on an empty instance.
solid answer
~40 sThe runtime gives `Nullable<T>` special boxing rules. When `HasValue` is false, converting to `object`, `ValueType` or an interface produces a **null reference**, not a box around an empty struct. When it is true, the box holds a plain `T`, so the box reports `System.Int32` and satisfies `is int` and `is IComparable`. Unboxing is symmetric: an `Int32` box unboxes into `int?`, and a null reference unboxes into an empty `int?`, while unboxing null to `int` throws `NullReferenceException`. `GetType()` is a non-virtual method on `object`, so calling it on an `int?` boxes first: it returns `System.Int32` for a non-empty instance and throws `NullReferenceException` for an empty one. `ToString()`, `Equals` and `GetHashCode` are overridden on the struct and work on an empty instance. To ask whether a type is nullable, use `Nullable.GetUnderlyingType(typeof(T))`; an instance cannot tell you.
code
csharp · 27 linesusing System;
int? missingAge = null;
int? age = 42;
object? boxedMissing = missingAge;
object boxedAge = age;
Console.WriteLine(boxedMissing is null); // True: no Nullable<int> box exists
Console.WriteLine(boxedAge.GetType()); // System.Int32
Console.WriteLine(boxedAge is IComparable); // True: the box is a plain Int32
int? back = (int?)boxedAge; // unbox an Int32 box into int?
int? none = (int?)boxedMissing; // null reference unboxes to an empty int?
Console.WriteLine($"{back} {none.HasValue}"); // 42 False
Console.WriteLine(missingAge.ToString() == ""); // True: called on the struct, no box
Console.WriteLine(Nullable.GetUnderlyingType(typeof(int?))); // System.Int32
try
{
Console.WriteLine(missingAge.GetType()); // CS8629 warning; boxes to null first
}
catch (NullReferenceException)
{
Console.WriteLine("GetType on an empty int? throws NullReferenceException");
}go deeper
Recall that converting an empty int? to object gives null and a non-empty one gives an ordinary boxed int.
Explain the two boxing rules, why GetType boxes but ToString does not, and which unboxing conversions succeed for int and int?.
Diagnose a NullReferenceException from GetType or an object-typed API fed an empty nullable, and detect nullable types with Nullable.GetUnderlyingType on the static type.
Weigh object-typed and reflection-based infrastructure against generics where nullable fields matter, since boxing erases the distinction such code needs.
## The two boxing rules **Boxing** copies a value type into a heap object so it can be used as `object`, `ValueType` or an interface. For `Nullable<T>` the runtime does not box the struct itself. The C# reference gives two rules: - If `HasValue` is `false`, boxing returns the **null reference**. Nothing is allocated. - If `HasValue` is `true`, boxing boxes the **underlying value** of type `T`, not the `Nullable<T>` instance. So `object boxed = (int?)42;` produces exactly the same kind of object as `object boxed = 42;`, and `object boxed = (int?)null;` produces `null`. With nullable warnings enabled, the compiler knows this: assigning a maybe-empty `int?` to a non-nullable `object` variable raises **CS8600**, because the result may be a null reference. ## What you can observe | Expression | `int? age = 42` | `int? age = null` | |---|---|---| | `(object)age` | an `Int32` box | `null` | | `((object)age).GetType()` | `System.Int32` | throws `NullReferenceException` | | `age.GetType()` | `System.Int32` | throws `NullReferenceException` | | `(object)age is int` | `true` | `false` | | `age.ToString()` | `"42"` | `""` | | `age.GetHashCode()` | 42 | 0 | | `age.Equals(null)` | `false` | `true` | The split in the table comes from where each method lives: - `ToString`, `Equals` and `GetHashCode` are **overridden** on `Nullable<T>`, so they run on the struct without boxing and handle the empty case themselves. - `GetType` is declared on `object` and is **not virtual**, so calling it on any struct boxes the struct first. For a nullable, that box is either an `Int32` or a null reference, and calling a method on null throws. With nullable warnings enabled, the compiler flags `age.GetType()` on a maybe-empty instance with **CS8629**, for exactly that reason. ## Unboxing back 1. An `Int32` box unboxes to `int` or to `int?`; both succeed. 2. A null reference unboxes to `int?` as an empty instance, but unboxing it to `int` throws `NullReferenceException`. 3. An `Int32` box cannot be unboxed to `long?` or `long`: unboxing must name the exact boxed type, so it throws `InvalidCastException`. ## Why the runtime does it this way If a boxed `Nullable<int>` existed, `object o = emptyAge; o == null` would be `false` even though the value is "null", and a boxed `int?` holding 42 would fail `o is int` checks that every other `int` box passes. Collapsing the box to `null` or to `T` keeps code written against `object` correct without knowing about nullables. The runtime's own source states the cost of the trick: because a boxed `Nullable<T>` can be used where a boxed `T` is, `Nullable<T>` implements **no interfaces at all**, since `T` may not implement them. ## Where the rules show up in everyday code - **Interface variables**: `IComparable? c = age;` boxes, so an empty `age` gives `c == null`, and calling `c.CompareTo` then throws `NullReferenceException`. - **`object` parameters**: a logging or formatting API that takes `object` receives either an `Int32` box or `null`; string interpolation `$"[{age}]"` prints `[]` for an empty value, because an empty nullable formats as an empty string. - **Collections of `object`**: an `ArrayList` or an `object[]` filled from `int?` values holds `null` entries for the empty ones, and no entry remembers that it came from a nullable. - **Equality through `object`**: `object.Equals((object)emptyAge, null)` is `true`, consistent with the box being `null`. ## Detecting a nullable type An instance cannot tell you it was an `int?`: its box is an `Int32` or `null`, and `is` cannot distinguish the two either (`o is int?` is `true` for any `Int32` box). Ask about the **static type** instead: - `Nullable.GetUnderlyingType(typeof(int?))` returns `typeof(int)`; for any type that is not a constructed `Nullable<T>`, including `typeof(int)` and the open `typeof(Nullable<>)`, it returns `null`. - Inside a generic method, `Nullable.GetUnderlyingType(typeof(T)) != null` tells you whether the caller passed a nullable value type. This is what serializers, mappers and validation code use when a survey model's `DateTime? LastLogin` must be treated differently from a required `DateTime`.
- Can an `Int32` box be unboxed into a `long?`?No. Unboxing must name the exact type that was boxed, or its nullable form: an `Int32` box unboxes to `int` or `int?`, and `(long?)box` throws InvalidCastException. Unbox to `int?` first, then convert with an ordinary numeric conversion.
- Why does `Nullable<T>` implement no interfaces, not even `IEquatable<T>`?Because a boxed `Nullable<T>` is just a boxed `T`, an interface reference to an `int?` is really a reference to an `Int32` box. If `Nullable<T>` declared an interface that `T` lacks, the box could not honour it. The runtime source carries a comment forbidding interfaces on `Nullable<T>` for that reason.
- Boxing an empty int? gives an object whose HasValue is false
- GetType() on an int? returns Nullable<int>
- Calling ToString() on an empty int? throws NullReferenceException
- Unboxing a null reference to int? throws
- You can tell an int? box from an int box with is