Recently while revising one of the concept I came across a situation which is interesting and I want to know why this happens.
We know one concept that we can't assign null values to Value types i.e. Struct
, int
, DateTime
, etc.
In order to assign null
we need nullable type i.e.
int i
should be replaced with Nullable<int> i = null
But if we see Nullable<T>
it is also of type struct
then how come null
can be assigned without stating any error? Why Microsoft contradicted it's own statement of "Null can't be assigned to value type"
If someone knows the reason behind this?
Because Nullable<T>
has compiler-level support; null
, in the context of Nullable<T>
, is essentially a value with a HasValue
flag of false
, where-as a non-null value has a HasValue
flag of true
. And similarly, "lifted" operators are derived from the defined operators. Likewise, Nullable<T>
has CLI support, in terms of boxing: a boxed Nullable<T>
with HasValue
of false
becomes null
, not a new box instance.
Basically: it all just comes down to because that is how they defined it should work.
People wanted nullable value types: Microsoft figured out a way for that to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With