Consider this contrived, trivial example:
var foo = new byte[] {246, 127}; var bar = foo.Cast<sbyte>(); var baz = new List<sbyte>(); foreach (var sb in bar) { baz.Add(sb); } foreach (var sb in baz) { Console.WriteLine(sb); }
With the magic of Two Complement, -10 and 127 are printed on the console. So far, so good. People with keen eyes will see me repeat the enumerated amount and add it to the list. This sounds like a ToList :
var foo = new byte[] {246, 127}; var bar = foo.Cast<sbyte>(); var baz = bar.ToList();
Except that this does not work. I get this exception:
Exception Type: System.ArrayTypeMismatchException
Message: The type of the source array cannot be assigned to the type of the target array.
I find this exception very peculiar because
ArrayTypeMismatchException - I do nothing with arrays. This is apparently an internal exception.Cast<sbyte> works fine (as in the first example), when using ToArray or ToList problem occurs.
I target .NET v4 x86, but the same thing happens in 3.5.
I do not need any advice on how to solve the problem, I already managed to do it. I want to know why this happens in the first place?
EDIT
Even stranger, adding a meaningless select statement, the ToList works correctly:
var baz = bar.Select(x => x).ToList();
casting c # linq
vcsjones Jun 14 '12 at 18:48 2012-06-14 18:48
source share