Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net Trouble casting ints do decimals

Why does this:

(new[]{1,2,3}).Cast<decimal>();

result in an

InvalidCastException: Specified cast is not valid.

like image 889
Ronnie Overby Avatar asked Mar 02 '10 16:03

Ronnie Overby


People also ask

Can an int be a decimal C#?

Integer type numbers are whole numbers without decimal points. It can be negative or positive numbers.

Does int () always round down?

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.


2 Answers

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.

like image 53
Jon Skeet Avatar answered Oct 16 '22 05:10

Jon Skeet


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);
like image 42
David Morton Avatar answered Oct 16 '22 05:10

David Morton