Cast object type in C #

Today I ran into a problem, and I did not quite understand why this would not work.

The following code example will work:

static void Main(string[] args) { int i32 = 10; object obj = i32; long i64 = (long)obj; } 

This will throw an InvalidCastException. Why is this not working? Is C # smart enough to know that an object is really of type int?

I already came up with a workaround, but I'm curious why the above code example didn't work in the first place.

Thanks Tim

+7
casting c #
source share
3 answers

Int32 does not have a fill for Int64. Doing an intermediate push on int should work, because the compiler is ready 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):

 // 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 Eric Lippert's blog post about this.

+9
source share

Check out this Eric Lippert blog post for more details.

Its essence is that the compiler will be very slow to find out (by trial and error, since object can be anything at all), what type was put into the box, and whether it can be safely poured.

+3
source share

Do you mean the compiler or runtime?

Runtime is smart enough, so it throws an InvalidCastException . The compiler, however, cannot know exactly what type of your object is since you entered your int.

The types of boxing and unboxing values ​​that are treated as objects. Boxing a value type wraps it inside an instance of an object type reference.

So, since it is placed as an object, the compiler will not complain about it.

For more information on boxing and unpacking, see here:

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

+1
source share

All Articles