SafeCast for Linq
Imagine
class A{}
class B:A{}
You have an IEnumerable<B> (by select), but a method needs IEnumerable<A>. Your only Linq-Option is:
myEnumerable.Cast<A>();
But as you refacture your code and B does not inherit from A any more, you will get an runtime error. The extension method is really simple, but it would be nice to have it in the standard library:
IEnumerable<TBase> SafeCast<TBase,TChild>(this IEnumerable<TChild> enumerable) where TChild:TBase
{
foreach(TChild c in enumerable)
yield return c;
}
1
vote
1 comment
-
Immo Landwerth (MSFT)
commented
Did you try Enumerable.OfType()?