Why does this:
(new[]{1,2,3}).Cast<decimal>();
result in an
InvalidCastException: Specified cast is not valid.
Integer type numbers are whole numbers without decimal points. It can be negative or positive numbers.
However, INT actually is more sophisticated than that. INT rounds a number down using the Order rounding method. That is, it rounds a positive number down, towards zero, and a negative number down, away from zero. Therefore, it's easy to use INT to round a number up using the Math method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With