I suggest you ...

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;
}

2 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Steffen GuhlemannSteffen Guhlemann shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    2 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Steffen GuhlemannSteffen Guhlemann commented  ·   ·  Flag as inappropriate

        Enumerable.OfType is not my point - it filters out of a list possibly containing anything some elements of a certain type. If due to some refactoring the inheritance structure changes, Enumerable.Cast will give me an runtime exception and Enumerable.OfType an empty result. This is even worse than an exception, since it is much harder to find such bugs.
        In the case, my inheritance hierarchy changes i want a immediate compiler error - and that is easily possible, if i am able to state in the cast, that i intend to cast this into a base type.

      Feedback and Knowledge Base