Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting object to int throws InvalidCastException in C#

I have this method:

private static Dossier PrepareDossier(List<List<object>> rawDossier)
{
    return new Dossier((int)rawDossier[0][0]);
}

When I use it I get an InvalidCastException. However, when I use Convert.ToInt32(rawDossier[0][0]) it works just fine. What is the problem?

like image 525
Michael Haddad Avatar asked Oct 06 '16 08:10

Michael Haddad


2 Answers

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.

like image 191
Lasse V. Karlsen Avatar answered Sep 21 '22 08:09

Lasse V. Karlsen


I would guess this is because the object in your list is not an int.

Convert.ToInt32 will convert other non-int types so works.

Check what is being passed in to the method.

like image 39
Justin Harvey Avatar answered Sep 19 '22 08:09

Justin Harvey