Consider the following enum declaration and int array:
enum Test { None };
int[] data = {0};
To convert this int[]
array to an Test[]
array we can simply do this:
Test[] result = Array.ConvertAll(data, element => (Test)element);
I initially tried to do this:
Test[] result = data.Cast<Test>().ToArray();
However, that throws an exception at runtime:
System.ArrayTypeMismatchException: Source array type cannot be assigned to destination array type.
Question One
Is there a way to do this using Linq and Cast<>
without an error, or must I just use Array.Convert()
?
Question Two (added after the first question was answered correctly)
Exactly why doesn't it work?
It seems like it's a case of an implementation detail escaping... Consider:
This causes an error:
var result = data.Cast<Test>().ToList(); // Happens with "ToList()" too.
But this does not:
var result = new List<Test>();
foreach (var item in data.Cast<Test>())
result.Add(item);
And neither does this:
var result = data.Select(x => x).Cast<Test>().ToList();
The clear implication is that some kind of optimisation is being done in the .ToList()
implementation that causes this exception.
Addendum:
This also works:
List<int> data = new List<int>{0};
var result = data.Cast<Test>().ToList();
or
List<int> data = new List<int>{0};
var result = data.Cast<Test>().ToArray();
It's only if the original data is an array that it doesn't work.