3

Possible Duplicate:
Puzzling Enumerable.Cast InvalidCastException

Why does

List<long> numbers = Enumerable.Range(1, 9999).Cast<long>().ToList();

fail with an InvalidCastException?

Community
  • 1
  • 1
VVS
  • 19,405
  • 5
  • 46
  • 65
  • Duplicate of [Puzzling Enumerable.Cast InvalidCastException](http://stackoverflow.com/questions/445471/puzzling-enumerable-cast-invalidcastexception) – jason Dec 13 '10 at 21:30
  • This is a duplicate of a [question](http://stackoverflow.com/questions/445471/puzzling-enumerable-cast-invalidcastexception) that I previously asked. – jason Dec 13 '10 at 21:31

1 Answers1

15

See this answer: Puzzling Enumerable.Cast InvalidCastException

In summary, Cast() works on the non-generic IEnumerable, which boxes each int as an Object. So, when the Cast is called it can only treat the elements as being of type Object, which cannot be cast to long.

The solution is to use Select to perform an explicit cast of each strongly-typed element:

var numbers = Enumerable.Range(1,9999).Select(i=>(long)i).ToList();
KeithS
  • 70,210
  • 21
  • 112
  • 164
  • So .cast<>() cannot be used on primitive types in general. Such a nice insight. I would go as far as creating an extension method for this sort of thing. Cheers. – XDS Nov 11 '18 at 13:45