casting from object

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

Can somebody tell me why this
Object o = 1;
long d = (long)o;

doesn't work.
Here I know that the value 1 is copied and created on the heap and
the reference o which exist on the stack is refering to the created memory
on the heap.
I know that this will throw invalidcastException and the cast must have
exactly the same type
in this case int.
But I mean that assigning an int to a long would'n be too bad so
the run time could exept it.

I mean this works fine assigning an int to long
int i = 1;
long l = i;

//Tony
 
Tony Johansson said:
Can somebody tell me why this
Object o = 1;
long d = (long)o;

doesn't work.
Here I know that the value 1 is copied and created on the heap and
the reference o which exist on the stack is refering to the created memory
on the heap.
I know that this will throw invalidcastException and the cast must have
exactly the same type
in this case int.
But I mean that assigning an int to a long would'n be too bad so
the run time could exept it.

Unboxing has to be precise - the cast above is an unboxing cast instead
of a conversion cast.

You can change the code to this, however, which will work:

object o = 1;
long d = (int) o;
I mean this works fine assigning an int to long
int i = 1;
long l = i;

And that implicit conversion is why my code above will work.
 
Back
Top