Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Types in .Net Programming Language [duplicate]

Tags:

c#

.net

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?

like image 974
user2485435 Avatar asked Jun 24 '14 12:06

user2485435


1 Answers

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.

like image 122
Marc Gravell Avatar answered Sep 30 '22 04:09

Marc Gravell