Casting object to int throws InvalidCastException in C#

The problem is that you don’t cast an object to an int, you’re attempting to unbox an int.

The object really has to be an int. It cannot be just anything that can be converted to an int.

So the difference is that this:

int a = (int)obj;

Really needs obj to be a boxed int, nothing else, whereas this:

int a = Convert.ToInt32(obj);

Will execute the ToInt32 method which will try to figure out what is really going on and do the right thing.

The “right thing” here is to ensure the object in question implements IConvertible and calling IConvertible.ToInt32, as is evident from the reference source:

public static int ToInt32(object value) {
    return value == null? 0: ((IConvertible)value).ToInt32(null);
}

You can see the unboxing on try roslyn:

IL_0007: unbox.any [mscorlib]System.Int32

Conclusion: The object you’re trying to unbox is not an int, but it is something that can be converted to an int.

Leave a Comment