Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting object type in c#

Tags:

c#

casting

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

like image 469
Tim Avatar asked Oct 12 '10 13:10

Tim


2 Answers

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.

like image 190
Ani Avatar answered Oct 10 '22 18:10

Ani


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.

like image 3
Adam Lear Avatar answered Oct 10 '22 17:10

Adam Lear