Why are Nullable<T> considered a value type?

.net, nullable

Solution

`System.Nullable<T>` is technically a structure, so it's a value type (the `null` value for a `Nullable<T>` is not exactly the same thing as a null reference. It's a boolean flag that denotes the lack of a value.) However, it's treated specially by the runtime and this makes it an awkward value type. First, it doesn't satisfy `where T : struct` type constraint (it doesn't satisfy `where T : class` either, for what it's worth). Second, it exhibits an interesting boxing behavior. Boxing a `Nullable<T>` will result in:

- A `null` reference, if the value is `null`.

A boxed value of the underlying type if it actually contains a value. That is, in the statements:

int? x = 2;
object y = x;

`y` is not a boxed `Nullable<int>`. It's simply a boxed `int`. You can unbox any boxed value of type `T` to `Nullable<T>` (and `T`, of course). Casting a `null` reference to `Nullable<T>` results in a `null` value (as you might expect).

This special treatment by the runtime makes nullable types work more similar to the way `null` works in reference types.

Problem

Have you ever tried to use the `Convert.ChangeType()` method to convert a value to a `Nullable<T>` type? Awkwardly, it will throw an `InvalidCastException` saying "Null object cannot be converted to a value type". Try running this on your immediate window: `?System.Convert.ChangeType(null, typeof(int?))` For some obscure reason, Nullables are considered value types. For example, `typeof(int?).IsValueType` returns `true`. For me, since `Nullable<T>` accept `null`, it's a class type, not a value type. Does anyone know why it would implemented differently?

Original source

Related problems