Reputation: 2236
following code behaves strange (at least for me):
int testValue = 1234;
this.ConversionTest( testValue );
private void ConversionTest( object value )
{
long val_1 = (long) (int) value; // works
long val_2 = (long) value; // InvalidCastException
}
I don't understand why the direct (explicit) cast to long doesn't work. Can someone explain this behaviour?
Thanks
Upvotes: 2
Views: 251
Reputation: 269368
The value
parameter of your ConversionTest
method is typed as object
; this means that any value types -- for example, int
-- passed to the method will be boxed.
Boxed values can only be unboxed to exactly the same type:
(long)(int)value
you're first unboxing value
to an int
(its original type) and then converting that int
to a long
.(long)value
you're attempting to unbox the boxed int
to a long
, which is illegal.Upvotes: 3