(ushort)...">

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
casting linq extension-methods linq-to-objects
source share
1 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 on IEnumerable , not IEnumerable<T> . This means that the time each value reaches the point where it is thrown, it has already been placed back in System.Object

+12
source share

All Articles