What exactly is going on here?
double d = 5; double? d2 = d as double?;
Ok, let it go through this.
In the first line, you declare a local variable named d of type double. You assign it a constant integer 5. The compiler converts the constant integer 5 to double 5.0 for you and generates a code that assigns a value to the local one.
In the second line, you declare a local variable named d2 of type double ?.
The expression "d is like double?" equivalent to "d is double ?? (double?) d: (double?) null", except that "d" is evaluated only once.
Part of what reads "d double?" evaluates to true because d is known to be of type double. (When "x is y" is given, if x is of type with a null value and y is the corresponding type of NULL, then the result is always true.)
The compiler knows about this and therefore discards the alternative to "(double?) Null". So the generated code looks like you said
double? d2 = (double?)d;
This is generated by calling the constructor double ?, passed to d as an argument to the constructor, and referencing the local variable d2 as "this". Thus, it becomes essential:
double? d2 = new Nullable<double>(d);
This is exactly what happens there. Does all this make sense?
source share