-3

I'm trying to do the following

int num = 20;
object number = num;
int result = (int)num;

It's yelling "Invalid cast" at me because, from what the compiler says:

Unable to cast object of type 'System.Int64' to type 'System.Int32

Can you please explain why my Int32 became an Int64?

mororo
  • 1,074
  • 2
  • 11
  • 28

1 Answers1

1

object number = num; is not a cast, but boxing!

While all reference types inherit from Object - explicitly or implicitly Value Types do not have a inheritance chain. Instead they get boxed into a instance of...something. That is then cast into the object.

And apparently that instance takes Int64 rather then Int32. For one reason or another, the option to put a Int32 into a Box that takes only Int32 is never even considered.

There is no longer a real reason to do this anyway. With things like Generics, you can get around most needs to box value types ever.

Christopher
  • 9,634
  • 2
  • 17
  • 31