There have been a couple of times where I've been curious about the .Cast<T>
LINQ extension method. I think to myself "that sounds like just what I need in this situation" but whenever I try to use it I always end up getting an InvalidCaseException
. I have never been able to use this method successfully. Here's an example line which checks the exception:
Enumerable.Range(0,10).Cast<float>().ForEach(Console.Out.WriteLine);
There is nothing controversial about casting an int
to a float
, so why does this method refuse to do it? I can work around this and get the desired effect by simply replacing the .Cast<float>
with a .Select(x => (float)x)
Enumerable.Range(0, 10).Select(x => (float)x).ForEach(Console.Out.WriteLine);
That isn't too much hassle, but still, I just don't get why the Cast<float>
method can't do the job for me.
The question in a nutshell: How do you use the .Cast<T>
extension method?
It's not relevant to the question, but just in case someone wants to know, I used a custom ForEach extension method in those code snippets up above (the standard one only works with lists):
static class Extensions
{
public static void ForEach<T>(this IEnumerable<T> x, Action<T> l)
{
foreach (var xs in x) l(xs);
}
}