If a float is assigned to a double, it accepts it, but if the float is first assigned to an object and then cast to double, it gives an InvalidCastException.
Can someone please clarify this?
float f = 12.4f;
double d = f;//this is ok
//but if f is assigned to object
object o = f;
double d1 = (double)o;//doesn't work, (System.InvalidCastException)
double d2 = (float)o;//this works
Implicit numeric conversion
float f = 12.4f;
double d = f;//this is ok
Unboxing conversion
object o = f;
double d1 = (double)o;//doesn't work, (System.InvalidCastException)
An unboxing operation to a non_nullable_value_type consists of first checking that the object instance is a boxed value of the given non_nullable_value_type, and then copying the value out of the instance.
In other words it checks if o
is boxed from double
, obviously not in this case.
More about conversions here.
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