I have the following code:
int intNumber1 = 100;
object intNumber2 = 100;
bool areNumberOfTheSameType = intNumber1.GetType() == intNumber2.GetType(); // TRUE
bool areEqual = intNumber1.Equals(intNumber2); // TRUE
long longNumber1 = (long) intNumber1; // OK
long longNumber2 = (long) intNumber2; // InvalidCastException. Why?
Why doesn’t the second cast work? I realize that it might be because the object doesn’t have an explicit cast to a long, but if we look at its type on runtime it is System.Int32.
If I use var or dynamic instead of object, it works.
Any thoughts?
Cast from
inttolongis interpreted as conversion between the two types.Cast from
objecttointis interpreted as unboxing a boxedint.It is the same syntax, but it says two different things.
In the working cases (
int→long,object(boxedint)→int), the compiler knows exactly what code to produce. If boxedint→longwas to work, the compiler would have to somehow figure out which conversion to use, but it doesn’t have enough information to do it.See also this blog post from Eric Lippert.