1

The following code gives an InvalidCast Exception

int newValue = new List<decimal>() { 6m }.Cast<int>().FirstOrDefault();

Even though decimal can be casted int, why can it not be done in a list?

Edit: To clear up the question, I want to know why the cast part of the equation throws an exception. Just running new List<decimal>() { 6m }.Cast<int>().ToList() Would also give an InvalidCast Exception

Lourens
  • 1,510
  • 1
  • 13
  • 27
  • Int can be casted as decimal but no the inverse. you are looking for `int newValue = new List() { 6m }.Select(v=>Convert.toDecimal(v)).FirstOrDefault();` – Franck Jan 23 '15 at 13:12
  • Covariance and Contravariance in Generics https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx – Anton Sizikov Jan 23 '15 at 13:13
  • @Franck That should be posted as an answer, not as a comment. It may not even be what the OP is looking for, though, and even if it is, it's a poor method of doing so. –  Jan 23 '15 at 13:13
  • 1
    @Franck also, you can actually cast both ways. Difference is, from Int to Decimal is implicit, whereas from Decimal to Int has to be hard-casted. Aka. (int)decimalVariable – Falgantil Jan 23 '15 at 13:14
  • @BjarkeSøgaard i should have specified it couldn't be cast implicitly. anyhow that's a wierd piece of code he should use `int value = 6;` and it should even be a constant :) – Franck Jan 23 '15 at 13:17

1 Answers1

6

You need:

new List<decimal>() { 6m}.Select(d => (int)d).ToList<int>();

or

new List<decimal>() { 6m}.ConvertAll(d => (int)d);

use Select with any IEnumerable, ConvertAll will only work with List

.Cast should be used when you need to process members of (for example) an array list as if they were strongly typed.

thanks to @hvd for correcting me

paul
  • 21,653
  • 1
  • 53
  • 54
  • No, the OP definitely isn't trying to cast `List` to `int`. And if all of the elements in the list should be converted (it's not clear to me whether that's what the OP wants), `.ConvertAll(...)` is often a better option than `.Select(...).ToList()`, and probably is here. –  Jan 23 '15 at 13:15