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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With