Does anyone know whether a double is implicitly cast to double? (Nullable type)
EDIT: What exactly is going on here?
double d = 5;
double? d2 = d as double?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well, let’s go through it.
In the first line, you declare a local variable named d of type double. You assign the constant integer 5 to it. The compiler converts the constant integer 5 to the double 5.0 for you and generates code which assigns the value to the local.
In the second line you declare a local variable named d2 of type double?.
The expression “d as double?” is equivalent to “d is double? ? (double?)d : (double?) null” except of course that “d” is only evaluated once.
The portion of that which reads “d is double?” is evaluated as true, because d is known to be of type double. (When asked “x is y”, if x is of a non-nullable type and y is the corresponding nullable type then the result is always true.)
The compiler knows this and therefore discards the alternative “(double?) null”. Therefore the code generated is as though you’d said
This is generated by calling the constructor of double?, passing in d as the argument to the constructor, and a reference to local variable d2 as “this”. So this becomes essentially:
That is exactly what is going on there. Does that all make sense?