Are double and double? interchangeable?

As stated above - Does anyone know if double double duplication is doubled? (Nullable type)

EDIT: What exactly is going on here?

double d = 5;

will double? d2 = d how double?

+4
source share
4 answers

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?

+6
source

They are not interchangeable according to your name.

double? there an implicit conversion from double to double? .

double? there an explicit conversion from double? to double .

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

Interestingly, although Nullable<T> does provide these transformations as user-defined transformations in the usual way, the MS C # compiler does not use them - it calls the Nullable<T>(T value) constructor for the implicit conversion and uses the Value property directly to explicitly convert the other way around.

+17
source

Yes, double implicitly added to double? . For instance. if d is double , then double? nullableD = d; double? nullableD = d; excellent.

Although double? implicitly displayed in double . In this case, you should use double d = nullableD.Value;

+3
source

You can do it as follows

  double? d; d = 12.00 double d2 = (double)d; 

Be careful before throwing them in double? may be zero; better to do this check


  if(d.HasValue) { double d2 = (double)d; } 
+2
source

Source: https://habr.com/ru/post/1300933/


All Articles