24
votes

Maybe I'm crazy, but I thought this was a valid cast:

(new int[]{1,2,3,4,5}).Cast<double>()

Why is LinqPad throwing a

InvalidCastException: Specified cast is not valid.

?

1
Also see why-cant-i-unbox-an-int-as-a-decimal. Very closely related.. - nawfal

1 Answers

37
votes

C# allows a conversion from int directly to double, but not from int to object to double.

int i = 1;
object o = i;
double d1 = (double)i; // okay
double d2 = (double)o; // error

The Enumerable.Cast extension method behaves like the latter. It does not convert values to a different type, it asserts that values are already of the expected type and throws an exception if they aren't.

You could try (new int[]{1,2,3,4,5}).Select(i => (double)i) instead to get the value-converting behaviour.