When trying to answer this question, I discovered the following:
string s = "test";
var result1 = s.Select(c => (ushort)c); // works fine
var result2 = s.Cast<ushort>(); // throws an invalid cast exception
Why does Cast<T>()
fail here? Whats the difference?
Think you will find your answer here:
Puzzling Enumerable.Cast InvalidCastException
The last part, under Edit:
Cast<T>()
is an extension method onIEnumerable
rather thanIEnumerable<T>
. That means that by the time each value gets to the point where it's being cast, it has already been boxed back into aSystem.Object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With