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.
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.
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