Search code examples
c#collectionspolymorphismabstraction

How can I get Polymorphic behavior with collections of custom polymorphic types?


I have a Superclass, Super with a Subclasses SubA

public class Super{}

public class SubA : Super{}

I want to have an interface that defines some actions on collections of Super.

public interface IDoer
{
    List<Super> GetObjects();
    void SaveObjects(List<Super> items);
}

So basically, I want to be able to polymorphically pass around collections of Supers, but List<SubA> is not a List<Super>. So my subADoer doesn't implement the IDoer.

public class SubADoer : IDoer
{
    public List<SubA> GetObjects{ return new SubA()}
    public void SaveObjects(List<SubA> items){//save}
}

How can I abstract Lists (or some other collection type) of my objects that sort of mirror the relationship between the types that compose them?


Solution

  • You need to use generics, like this:

    public interface IDoer<T> where T : Super
    {
        List<T> GetObjects();
        void SaveObjects(List<T> items);
    }
    
    public class SubADoer : IDoer<SubA>
    {
        public List<SubA> GetObjects()
        {
            // ...
        }
    
        public void SaveObjects(List<SubA> items)
        {
            // ...
        }
    }