tags:

views:

91

answers:

4

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

+6  A: 

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.

Ani
+1  A: 

You mean the compiler or the runtime?

The runtime is smart enough, so it throws the InvalidCastException. The compiler however cannot know for sure what type your object is, since you boxed your int.

Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type.

So since its boxed as an object, the compiler won't complain about it.

See more information on boxing and unboxing here:

http://msdn.microsoft.com/en-us/library/yz2be5wk%28VS.80%29.aspx

Arcturus
A: 

C# was a static language till .net 4.0

if you dynamic instead of object in c# 4.0 , it will work

saurabh
+3  A: 

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.

Anna Lear