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?
System.Nullable<T>is technically a structure, so it’s a value type (thenullvalue for aNullable<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 satisfywhere T : structtype constraint (it doesn’t satisfywhere T : classeither, for what it’s worth). Second, it exhibits an interesting boxing behavior. Boxing aNullable<T>will result in:nullreference, if the value isnull.A boxed value of the underlying type if it actually contains a value. That is, in the statements:
yis not a boxedNullable<int>. It’s simply a boxedint. You can unbox any boxed value of typeTtoNullable<T>(andT, of course). Casting anullreference toNullable<T>results in anullvalue (as you might expect).This special treatment by the runtime makes nullable types work more similar to the way
nullworks in reference types.