Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting and Linq Cast<T>()

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?

like image 747
fearofawhackplanet Avatar asked Jul 29 '10 11:07

fearofawhackplanet


1 Answers

Think you will find your answer here:

Puzzling Enumerable.Cast InvalidCastException

The last part, under Edit:

Cast<T>() is an extension method on IEnumerable rather than IEnumerable<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 a System.Object

like image 146
Martin Ingvar Kofoed Jensen Avatar answered Oct 12 '22 11:10

Martin Ingvar Kofoed Jensen