Why does this:
(new[]{1,2,3}).Cast<decimal>();
result in an
InvalidCastException: Specified cast is not valid.
Why does this:
(new[]{1,2,3}).Cast<decimal>();
result in an
InvalidCastException: Specified cast is not valid.
Yup, Cast
doesn't do that. Basically it just does reference conversions and unboxing conversions - not conversions between different value types.
Use this instead:
(new[]{1,2,3}).Select(x => (decimal)x)
Note that pre-.NET 3.5 SP1, Cast
did some more conversions than it does now. I don't know offhand whether it would have worked then or not, but it definitely doesn't now.
Cast isn't convert.
When you use the Cast extension method, it's trying to cast an item based on the inheritance scheme. Since int doesn't derive from decimal, this can't be done using Cast. Try the following instead:
(new[] {1,2,3}).Select(x => (decimal)X);