Possible Duplicate:
Puzzling Enumerable.Cast InvalidCastException
Hi,
I just noticed something quite strange with the Enumerable.Cast<T> extension method… It seems that it can’t cast from int to long, even though this cast is perfectly legal.
The following code fails with an InvalidCastException :
foreach (var item in Enumerable.Range(0,10).Cast<long>())
{
Console.WriteLine(item);
}
But this code, which I assumed to be equivalent, does work :
foreach (var item in Enumerable.Range(0,10).Select(i => (long)i))
{
Console.WriteLine(item);
}
Can anyone explain that behavior ? I looked at the code of the Cast method with Reflector, but Reflector can’t interprete iterator blocks, so it’s pretty hard to understand…
The relevant line in
Cast:We can mimic this using the following code:
Which also fails. The key here is that at the point of cast, it’s an object. Not an int. This fails because we can only unbox from an object to the exact type we want. We are going from object – which could be a boxed long, but it’s not. It’s a boxed int. Eric Lippert discussed this on his blog:
In your code which works, you’re not dealing with a boxed int (an object), you’ve got an int.