Suppose I have classes A and B, which derives from A. Suppose I have a method that operates on collections of A's. I'd like to pass it a collection of B's. How can I do that?

In other words:

class A {}
class B : A {}

    void doAStuff(List<A> someAs) { // do stuff }

     List<B> b = new List<B>();
     doAStuff(b); // won't compile

I come to C# from Java, where doAStuff would be coded

void doAStuff(List<? extends A> someAs) { }

and I could pass it a list of B's. Is there a way to do that in C#?

You are trying to pass a "List<B>" type to your method when it is defined as accepting argument "List<A>". If class B contains a List of A's, you could define:

public class A {}
    public class B : List<A>
    {
       
        void doAStuff(List<A> someAs)
        { // do stuff }

        List<B> b = new List<B>();
        doAStuff(b[0]); // compiles
     }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.