Accepted answer

because you're typecasting from an int to double, it's not a conversion it's a type cast and this is somewhat different from when you cast int to double in the general case.

the cast<t> extension method uses the il instruction unbox.any

while a c# cast like this

var x = (double)42;

actually results in the il instruction


fundamentally unboxing an type as a different type is wrong and that's why you get the exception.

this question has the same answer and also links to a blog post by eric lippert.


there is a difference between a .net framework type-cast and a c# type conversion. they are not the same. "casting" int to double is a feature of the c# language, and of the language alone.

the c# compiler can convert an int to double using a special instruction for this purpose. the compiler knows, at compile time, that the source type is "int", the destination type is "double", and therefore can generate the proper instruction. this is not really a type cast in the .net framework sense.

system.int32 cannot be type-cast to system.double. the cast extension method was compiled without knowing the exact types of the source and the destination collections, and therefore no special instructions for handling c# specific features were generated. the only code that is generated for the cast extension method is a normal .net type cast (casting classes to their base types, casting to object, and casting types to the interfaces they implement).


list contains ints, which you attempt to cast to double. change your query to

var query = => (double)d);


here's the source for enumerable.cast (.net 4):

public static ienumerable<tresult> cast<tresult>(this ienumerable source) { 
    ienumerable<tresult> typedsource = source as ienumerable<tresult>;
    if (typedsource != null) return typedsource; 
    if (source == null) throw error.argumentnull("source");
    return castiterator<tresult>(source);

static ienumerable<tresult> castiterator<tresult>(ienumerable source) {
    foreach (object obj in source) yield return (tresult)obj; 

as you can see, the castiterator attempts to cast an object (which in this case is a boxed int) to a double. unboxing operations only succeed if the target type is exactly the same as the original type that was boxed, so an exception is thrown. this link that john leidegren provided explains in detail.

Related Query

More Query from same tag