Covariance in List

How can we design following model properly? I have two class Library. Library 2 has reference of Library 1. But Library 1 doesn't have reference of Library 2.

Library 1:

public class BaseData
{
   /*Some Properties*/
}

public class BaseGroup
{
   /*Some data*/
   public List<BaseData> DataList;
}

Library 2:

public class ChildData : BaseData
{
   /*Some more data*/
}

public class ChildGroup
{
   /*Some more data*/
   public List<ChildData> DataList;
}

How can I design these models so that I have one List. The List can be initiated at Library 1 and later updated at Library 2. Also from Library 2, I need to pass the ChildGroup object to Library 1 methods which takes BaseGroup as an argument.

Jon Skeet
people
quotationmark

You can't make List<T> covariant - it's invariant, and there's nothing you can do about that. You can't treat a List<Apple> as a List<Fruit> because you can't call list.Add(new Orange()) on it, for example.

It seems to me that you should make your baseGroup class generic, with a constraint. Then you can make childGroup derive from it:

So - having fixed up the class names to follow .NET naming conventions:

public class BaseData {}

public class BaseGroup<T> where T : BaseData
{
    public List<T> DataList;
}

public class ChildData : BaseData {}

public class ChildGroup : BaseGroup<ChildData>
{
    // No need for a separate list here
}

people

See more on this question at Stackoverflow