Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of null values in Convert.ToDouble is not correct, is it possible?

Tags:

c#

It is curious, friday I was working in the project of my company and I found some "bad" code or curious code. I said, I don't believe that error in Microsoft Framework.

I found that:

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

This result of test is 0.0 instead of exception error.

I was surprised because I expected some kind of exception.

Can somebody tell me why does it happen?

like image 898
David Avatar asked Aug 30 '14 17:08

David


2 Answers

It is all about how Convert.ToDouble(object) method's 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 that is equivalent to value, or zero if value is null.

like image 152
Soner Gönül Avatar answered Nov 13 '22 23:11

Soner Gönül


Can somebody tell me why does it happen?


Because that's the documented behaviour:

Whether it's Convert.ToDouble(Object) or Convert.ToDouble(Double), the documentation states quite clearly:

(Under return value)

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

As always, if reality doesn't match expectations, the first thing you should do is check whether your expectations match the documented behaviour.

It may have a genuine reason why it behaves that way.

Some people argue:


I don't think there is a good reason for it to behave that way

That may be valid opinions, but if the framework designers genuinely thought that returning zero was a non-ideal result, they should have done whatever they thought best.

Obviously once the behavior was defined in .NET, it couldn't be changed for later versions - but that's not the same as saying it had to behave the same way as VB6.

like image 35
canolucas Avatar answered Nov 14 '22 00:11

canolucas