The behavior of null values ​​in Convert.ToDouble is wrong, is this possible?

It is curious that on Friday I worked in the project of my company, and I found some kind of "bad" code or a curious code. I said, I do not believe this error in the Microsoft Framework.

I found that:

double? euros = null; double test = Convert.ToDouble(euros); 

This test result is 0.0 instead of an exception error.

I was surprised because I was expecting some kind of exception.

Can someone tell me why this is happening?

+5
source share
3 answers

Can someone tell me why this is happening?


Because this is documented behavior:

Be it Convert.ToDouble(Object) or Convert.ToDouble(Double) , the documentation says quite clearly:

(Under the return value)

A double-precision floating-point number equivalent to a value, or zero if the value is zero .

As always, if reality does not meet expectations, the first thing you should do is check if your expectations are consistent with documented behavior.

He may have a genuine reason why he behaves this way.

Some people claim:


I don’t think there are good reasons for this.

This may be the right opinion, but if the framework designers genuinely believed that returning zero was not an ideal result, they should have done everything they considered the best.

Obviously, once the behavior was defined in .NET, it could not be changed for later versions - but this is not the same as saying that it should behave just like VB6.

+8
source

It's all about how the Convert.ToDouble(object) method is implemented ;

 public static double ToDouble(object value) { return value == null? 0: ((IConvertible)value).ToDouble(null); } 

As you can see, it returns 0 if value is null .

Also documented as;

Return value

A double-precision floating-point number is equivalent to a value, or zero if the value is null .

+10
source

If you want your code to throw an exception when null , you need to cast to double instead of using Convert.ToDouble() .

The following code will throw an exception that seems to be what you want:

 double? euros = null; double test2 = (double)euros; // System.InvalidOperationException: 'Nullable object must have a value.' 
0
source

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


All Articles