This throws an exception that say the source can't be casted to destination:
int a = 1;
object b = (object)a;
float c = (float)b; // Exception here
Why?
This throws an exception that say the source can't be casted to destination:
int a = 1;
object b = (object)a;
float c = (float)b; // Exception here
Why?
You can only cast boxed structs to the exact type, so you'll need to cast a to int first:
float c = (float)(int)b;
However since there's an implicit conversion to float from int, you can just do:
float c = (int)b;
As far as I know it's because you box "a" as an int and after that you unbox it as a float and this wont work...
to get it right you should do float c = (float) (int) b;
You can't unbox (cast to object and back) a value from one data type to another. You would need to bring it back to its original type first, then pull it out. Alternatively, you can use the Convert.To*
methods, e.g.
Object a = 6;
Double b = Convert.ToDouble(a);
Follow-up: http://www.ideone.com/hgeob
The problem is that the same syntax is reused for 3 operations (historical problem from C):
int a = 1; // Ok
object b = (object)a; // Ok. int is struct so we may box it into object
float c = (float)a; // Ok. Conversion from integer to float
float c = (float)b; // Error. object b is not boxed float