tags:

views:

600

answers:

3

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

+7  A: 

The relevant line in cast:

 this.<>2__current = (TResult)this.<obj>5__ab;

We can mimic this using the following code:

int foo = 1;
long bar = Cast<long>(foo); //oh noes!

T Cast<T>(object input)
{
    return (T)input;
}

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:

we’ve decided that unboxing can only unbox to the exact type. If you want to call the slow method that does all that goo, it’s available – you can always call Convert...

In your code which works, you're not dealing with a boxed int (an object), you've got an int.

Rex M
Indeed. Note that earlier release of the Cast<T> sequence operator *got it wrong* and accidentally allowed conversions like this to *succeed* when by design they should fail. (And it was also very, very slow.) That's the worst possible bug situation, where in order to make code behave correctly, you have to potentially break existing customers. We took the hit; the code is now correct and fast, not excessively lenient and slow, but we felt really bad about it. I feel particularly bad, since I code-reviewed the incorrect implementation and didn't catch the problems before the release. Sorry!
Eric Lippert
Of course, I forgot about the boxing... perfect explanation, thanks !
Thomas Levesque
Woohoo! I said something and Eric Lippert said "indeed". Just made my month :D
Rex M
Dude. Remain calm.
Eric Lippert
@anon why the DV?
Rex M
@Eric Lippert: Looks like you're going to just have to get used to your newfound celebrity status. ;)
jasonh
+3  A: 

Unlike most of the other LINQ extension methods, Cast extends the non-generic IEnumerable interface, rather than IEnumerable<T>.

This means that the int values generated by the Range call are boxed by the Cast call's underlying enumerator, which then attempts to cast them to long and fails, because values can only be unboxed to the exact same type.

You can mimic the same exception behaviour in your second loop by explicitly boxing the int values:

foreach (var item in Enumerable.Range(0, 10).Select(i => (long)(object)i))
{
    Console.WriteLine(item);
}
LukeH
Exactly ! but Rex M was first, sorry... Thanks anyway !
Thomas Levesque
This is the more correct explanation as to why. +1
Shaun Wilson
A: 

The problem is that CastIterator's MoveNext boxes the current value and attempts to unbox it to the target type (where the boxed value is not of the correct type) thus the unboxing fails during type checking.

Reference Info:

http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.unbox%5Fany.aspx

    L_003c: ldarg.0 
    L_003d: ldarg.0 
    L_003e: ldfld class [mscorlib]System.Collections.IEnumerator System.Linq.Enumerable/<CastIterator>d__aa<!TResult>::<>7__wrapac
    L_0043: callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
    L_0048: stfld object System.Linq.Enumerable/<CastIterator>d__aa<!TResult>::<obj>5__ab
    L_004d: ldarg.0 
    L_004e: ldarg.0 
    L_004f: ldfld object System.Linq.Enumerable/<CastIterator>d__aa<!TResult>::<obj>5__ab
    L_0054: unbox.any !TResult

The workaround is to use a Select()

Shaun Wilson