Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Convert.ToDouble vs (double)

I was surprised when exception error I was hitting using (double)value got fixed by changing it to System.Convert.ToDouble(value).

The value was object type.

Can anyone tell me why?

Here I attach the code and error message:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    return (double)value * (double)parameter;
}

Error Message: System.InvalidCastException: Specified cast is not valid.
like image 702
swcraft Avatar asked Jun 10 '13 23:06

swcraft


1 Answers

If you've boxed a value that is not a double, then try to unbox and cast in one operation, you will receive an exception:

int value = 42;
object val = value; // Box

double asDouble = (double)val; // This will raise an exception

For details, I'd recommend reading Eric Lippert's article Representation and Identity which discusses this in detail.

However, Convert.ToDouble will check the type, and handle this case, then convert the resulting integer value to a double without an exception:

int value = 42;
object val = value; // Box

double asDouble = Convert.ToDouble(val); // This will work fine.

This works by checking whether the object implements IConvertible, and, if so (Int32 does), using IConvertible.ToDouble, which in turn uses Int32's ToDouble implementation.

like image 51
Reed Copsey Avatar answered Sep 19 '22 19:09

Reed Copsey