views:

80

answers:

2

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?

A: 

I believe using the Cast() extension method only takes default (non-user cast), implicit casts into account or casts from a more general type (e.g., object). Otherwise it fails.

Turns out this is the case.

Jeff M
+6  A: 

Think you will find your answer here:

http://stackoverflow.com/questions/445471/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

Martin Ingvar Kofoed Jensen
Thanks Martin. That's interesting. So Cast<T> should probably be avoided anyway for the inherent boxing performance penalty. I'm suprised MSDN doesn't mention that anywhere (that I could find, anyway).
fearofawhackplanet
`Cast<T>` is only intended to be used for bringing an `IEnumerable` up to the level of an `IEnumerable<T>`, where all the other LINQ operators are defined. Taking an `IEnumerable<TOriginal>` and converting it to an `IEnumerable<TOther>` is a projection, which is done by `Select`. The fact that `Cast` is even possible on an `IEnumerable<T>` is merely because `IEnumerable<T>` inherits from `IEnumerable` - no other reason.
Stephen Cleary