I have the following code:
int intNumber1 = 100;
object intNumber2 = 100;
bool areNumberOfTheSameType = intNumber1.GetType() == intNumber2.GetType(); // TRUE
(Caution: Guess)
Int32
has a conversion operator to Int64
which is what gets invoked when you do the first cast. Object
doesn't, so your second cast is trying to cast an object to another type which isn't a supertype (Int64
doesn't inherit Int32
).
The reason why it works with var
is obvious – the compiler just saves you from typing int
in that case. With dynamic
the runtime does all necessary checks for what needs to be done while normally the compiler would just insert either the cast or invoke the conversion operator.