I ran into an issue today and I wasn't entirely sure why it wouldn't work.
The following code sample will crash:
static void Main(string[] args)
{
int i32 = 10;
object obj = i32;
long i64 = (long)obj;
}
This will result in an InvalidCastException. Why does this not work? Is C# not smart enough to know that the object is actually of type int?
I've already come up with a workaround, but I'm curious as to why the above code sample didn't work in the first place.
Thanks, Tim
There is no cast available from a boxed Int32 to an Int64.
Making an intermediate cast to int
should work, because the compiler is willing to generate this:
// verify obj is a boxed int, unbox it, and perform the *statically*
// known steps necessary to convert an int to a long
long i64 = (long) ((int)obj);
but not (hypothetically) this:
// Find out what type obj *actually* is at run-time and perform
// the-known-only-at-run-time steps necessary to produce
// a long from it, involving *type-specific* IL instructions
long i64 = (long)obj;
Here's a blog post by Eric Lippert about this.
Check out this blog post by Eric Lippert for the gory details.
The gist of it is that it would be very slow for the compiler to figure out (by trial and error, since object
can be anything at all) what type has been boxed and whether or not it can be safely cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With