1

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • 3
    possible duplicate of [Why \[ (int)(object)10m; \] does throw "Specified cast is not valid" exception?](http://stackoverflow.com/questions/3953391/why-intobject10m-does-throw-specified-cast-is-not-valid-exception) – Brad Christie Apr 11 '11 at 22:30

4 Answers4

5

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;
Lee
  • 142,018
  • 20
  • 234
  • 287
1

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;

Ivan Crojach Karačić
  • 1,911
  • 2
  • 24
  • 44
1

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

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

The problem is that the same syntax is reused for 3 operations (historical problem from C):

  1. Boxing/unboxing the value
  2. Converting numbers
  3. Casting

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
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
Maciej Piechotka
  • 7,028
  • 6
  • 39
  • 61
  • UL/OLs are funny with the parser, you need to add something between them. In this case I used an arbitrary bogus HTML tag (as to invoke formatting, but not interfere with the post itself). – Brad Christie Apr 11 '11 at 22:38