I have the following code:
int intNumber1 = 100;
object intNumber2 = 100;
bool areNumberOfTheSameType = intNumber1.GetType() == intNumber2.GetType(); // TRUE
That it doesn't work due to being two different types of casts (one converting, the other unboxing) has already been stated in answers here. What might be a useful addition, is that Convert.ToInt64()
will convert anything that is either a built-in type that can be converted to long, or a type of a class that implements IConvertible.ToInt64()
, into a long. In other words, if you want to be able to cast an object that contains an integer (of whatever size) to long, Convert.ToInt64()
is the way to go. It is more expensive, but what you are trying to do is more expensive that casting, and the difference is negliable (just big enough to be wasteful in cases where you know the object must be a boxed long).