8

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.
swcraft
  • 2,014
  • 3
  • 22
  • 43
  • Please include a sample of your code. – STLDev Jun 10 '13 at 23:54
  • 1
    possible duplicate of [When to use a Cast or Convert](http://stackoverflow.com/questions/3168704/when-to-use-a-cast-or-convert) – Keith Nicholas Jun 10 '13 at 23:54
  • My feeling it's because of the implicit cast that you're using, but for a proper answer, can you please post a sample of your code and also tell us what the exception was that you got ? – Russ Clarke Jun 10 '13 at 23:56
  • 1
    Unboxing a boxed value that's not a double to double is explicitly not supported by C#. It does work in VB.NET. This restriction is a big deal, it allows for much more efficient code since there is no need to go hunting for a way to convert the value. That mattered a great deal back in .NET 1.x, before generics. – Hans Passant Jun 10 '13 at 23:59

1 Answers1

25

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373