Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covariance in List

Tags:

c#

.net

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.

like image 573
Gulshan Avatar asked Dec 05 '22 20:12

Gulshan


1 Answers

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
}
like image 157
Jon Skeet Avatar answered Dec 08 '22 10:12

Jon Skeet