Search code examples
c#linqoftype

Parameter of OfType<????> when used in a method with C#


I have this code to get "A" as a filtered result.

public static void RunSnippet()
{
    Base xbase = new Base(); 
    A a = new A(); 
    B b = new B();
    IEnumerable<Base> list = new List<Base>() { xbase, a, b };
    Base f = list.OfType<A>().FirstOrDefault();
    Console.WriteLine(f);
}

I need to use IEnumerable<Base> list = new List<Base>() {xbase, a, b}; from a function as follows:

public static Base Method(IEnumerable<Base> list, Base b (????)) // I'm not sure I need Base b parameter for this?
{
    Base f = list.OfType<????>().FirstOrDefault();
    return f;
}

public static void RunSnippet()
{
    Base xbase = new Base(); 
    A a = new A(); 
    B b = new B();
    IEnumerable<Base> list = new List<Base>() { xbase, a, b };
    //Base f = list.OfType<A>().FirstOrDefault();
    Base f = Method(list);
    Console.WriteLine(f);
}

What parameter do I use in '????' to get the same result from the original code?


Solution

  • It seems like you are looking for a generic way to do what is in Method based on different children types of Base. You can do that with:

    public static Base Method<T>(IEnumerable<Base> b) where T: Base
    {
        Base f = list.OfType<T>().FirstOrDefault();
        return f;
    }
    

    This will return the first instance from b that is of type T (which has to be a child of Base).