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...