Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are double and double? interchangeable?

Tags:

c#

As above - 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?

like image 826
Jack Kada Avatar asked Feb 10 '10 23:02

Jack Kada


1 Answers

They're not interchangeable as per your title.

There is an implicit conversion from double to double?.

There is an explicit conversion from double? to double.

The same is true for all nullable value types: there's an implicit conversion from T to Nullable<T>, and an explicit one from Nullable<T> to T.

Interestingly, although Nullable<T> does provide those conversions as user-defined conversions in the normal way, the MS C# compiler doesn't use those - it calls the Nullable<T>(T value) constructor for the implicit conversion, and uses the Value property directly for the explicit conversion the other way round.

like image 113
Jon Skeet Avatar answered Oct 04 '22 19:10

Jon Skeet