6

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?

Community
  • 1
  • 1
fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253

1 Answers1

12

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

Community
  • 1
  • 1
  • 1
    Thanks Martin. That's interesting. So Cast 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 Jul 29 '10 at 11:46
  • 5
    `Cast` is only intended to be used for bringing an `IEnumerable` up to the level of an `IEnumerable`, where all the other LINQ operators are defined. Taking an `IEnumerable` and converting it to an `IEnumerable` is a projection, which is done by `Select`. The fact that `Cast` is even possible on an `IEnumerable` is merely because `IEnumerable` inherits from `IEnumerable` - no other reason. – Stephen Cleary Jul 29 '10 at 13:17