casting from object


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
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top