casting from object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tony Johansson

    casting from object

    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 invalidcastExce ption 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








  • Jon Skeet [C# MVP]

    #2
    Re: casting from object

    Tony Johansson <johansson.ande rsson@telia.com wrote:
    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 invalidcastExce ption 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.

    --
    Jon Skeet - <skeet@pobox.co m>
    Web site: http://www.pobox.com/~skeet
    Blog: http://www.msmvps.com/jon.skeet
    C# in Depth: http://csharpindepth.com

    Comment

    Working...