0

Does anyone knows why I can't cast an Int to an UInt by using the Linq extension method Cast<>()?

var myIntList = new List<int>();

myIntList.Add(1);
myIntList.Add(2);
myIntList.Add(3);

var myUIntList = myIntList.Cast<uint>().ToList();

It throws a Specified cast is not valid. When I'm using a Select(), it will work (ofcourse).

var myIntList = new List<int>();

myIntList.Add(1);
myIntList.Add(2);
myIntList.Add(3);

var myUIntList = myIntList.Select(i => (uint)i).ToList();

(is it a bug or not implemented feature?)

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57

1 Answers1

4

Enumerable.Cast is implemented as an extension method on IEnumerable (the non-generic interface).

This implication of this is that the values in the sequence are cast from object, which means boxing and unboxing is involved for value types. You can only unbox to the exact type. For example:

int i = 1;
object boxed = i;

int unboxToInt = (int)boxed; // ok
uint unboxToUint = (uint)boxed; // invalid cast exception

You can read more about boxing in the documentation.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45