The Nullable
type is defined as a struct
. In .Net, you can\'t assign null
to a struct
because structs
How did
Nullable<T>
become an exception to the rule "You can't assign null to a value type?"
By changing the language, basically. The null
literal went from being "a null reference" to "the null value of the relevant type".
At execution time, "the null value" for a nullable value type is a value where the HasValue
property returns false
. So this:
int? x = null;
is equivalent to:
int? x = new int?();
It's worth separating the framework parts of Nullable<T>
from the language and CLR aspects. In fact, the CLR itself doesn't need to know much about nullable value types - as far as I'm aware, the only important aspect is that the null value of a nullable value type is boxed to a null reference, and you can unbox a null reference to the null value of any nullable value type. Even that was only introduced just before .NET 2.0's final release.
The language support mostly consists of:
?
so int?
is equivalent to Nullable<int>
null
??
) - which isn't restricted to nullable value types