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
intshould work, because the compiler is willing to generate this:but not (hypothetically) this:
Here’s a blog post by Eric Lippert about this.