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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With