5

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?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
user2485435
  • 125
  • 9
  • 2
    Your compiler knows what a nullable value type looks like. It doesn't *actually* assign *null* to it. Use ildasm.exe to see what it really does. – Hans Passant Jun 24 '14 at 12:22

1 Answers1

19

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Does it need "compiler level support?" I'd assume it could be implemented just by overriding the equality operators/methods of a standard struct (though it's entirely possible that there are some compiler optimisations...). (I admit I've not looked at the IL/code for `Nullable` and probably should!) – Dan Puzey Jun 24 '14 at 12:22
  • @DanPuzey yes, it does; otherwise things like ` == null` / ` != null`, or any of the arithmetic etc operators: would not work. A regular struct is never null, for example. – Marc Gravell Jun 24 '14 at 14:50