Toto Toto - 2 months ago 5
C# Question

Why can you assign null to a Nullable variable?

Why the line below compile ? For me,

is a struct and we can't assign a variable of this type the value "null".

Nullable<double> someVar = null;

The assignation operator is not supposed to be overridable but maybe it is some syntax sugar and the compiler knows it has to change it to ?

Nullable<double> someVar = new Nullable<double>();
someVar.Value = null;


The compiler and language specification have special magical support that makes the null literal convertible to Nullable<T>.

The spec says:

  • A null literal. An expression with this classification can be implicitly converted to a reference type or nullable type.