Instantiate a List of Parent class with Subclass

I have the following class:

public abstract class ParentCollection
{
   public List<ParentObject> MyList { get; set; }

   public ParentCollection(){}
}

ParentObject has a subclass that inherits from it, ChildObject. ParentCollection also has the following subclass:

public class ChildCollection : ParentCollection
{
   public ChildCollection() : base()
   {
      this.MyList = new List<ChildObject>();
   }

   private void Filter()
   {
      this.MyList = this.Objects.Where(p => p.Age > 18).ToList();
   }
}

The line this.MyList = new List<ChildObject>(); is throwing a Cannot implicitly convert type error. The Filter() method is also throwing a type error.

My understanding is that the List of parent objects should allow for instantiation using the child object, since that object inherits from the parent.

Upvotes: 0

Views: 1099

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109577

The problem is that allowing write access to a list of a derived type through a base interface can let you add objects of the wrong type to the list.

However, if you only require enumerated read access to the list, you could do this:

public abstract class ParentCollection
{
    public IEnumerable<ParentObject> MyList
    {
        get;
        set;
    }

    public ParentCollection()
    {
    }
}

Upvotes: 1

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

The problem here is although ChildObject can be a child of ParentObject, List<ChildObject> is not a child of List<ParentObject>. List<ChildObject> is a object of type List and so is the List<ParentObject>

You can change your ParentCollection like this to achieve what you want.

abstract class ParentCollection
{
    public IEnumerable<ParentObject> MyList { get; set; }

    public ParentCollection() { }
}

You might also want to look into Covarience and Contravarience.

Upvotes: 2

Related Questions