Casting and Linq Cast <T> ()
While trying to answer this question, I found 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 is Cast<T>() not working? What is the difference?
+6
fearofawhackplanet
source share1 answer
Think you will find your answer here:
Puzzling Enumerable.Cast InvalidCastException
The last part, in the "Edit" section:
Cast<T>()is an extension method onIEnumerable, notIEnumerable<T>. This means that the time each value reaches the point where it is thrown, it has already been placed back inSystem.Object
+12
Martin Ingvar Kofoed Jensen
source share