Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an object which holds a float value be cast to double? [duplicate]

Tags:

c#

casting

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
like image 735
Sharwan Kami Avatar asked Jul 15 '19 06:07

Sharwan Kami


1 Answers

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.

like image 62
Johnny Avatar answered Oct 04 '22 21:10

Johnny