Generic List of Generic Interfaces not allowed, any alternative approaches?

P B picture P B · Dec 23, 2010 · Viewed 10.6k times · Source

I am trying to find the right way to use a Generic List of Generic Interfaces as a variable.

Here is an example. It is probably not the best, but hopefully you will get the point:

public interface IPrimitive<T>
{
     T Value { get; }
}

and then in another class, I want to be able to declare a variable that holds a list of objects that implement IPrimitive<T> for arbitrary T.

// I know this line will not compile because I do not define T   
List<IPrimitive<T>> primitives = new List<IPrimitives<T>>;

primitives.Add(new Star());   // Assuming Star implements IPrimitive<X>
primitives.Add(new Sun());    // Assuming Sun implements IPrimitive<Y>

Note that the T in IPrimitive<T> could be different for each entry in the list.

Any ideas on how I could setup such a relationship? Alternative Approaches?

Answer

Josh picture Josh · Dec 23, 2010
public interface IPrimitive
{

}

public interface IPrimitive<T> : IPrimitive
{
     T Value { get; }
}

public class Star : IPrimitive<T> //must declare T here
{

}

Then you should be able to have

List<IPrimitive> primitives = new List<IPrimitive>;

primitives.Add(new Star());   // Assuming Star implements IPrimitive
primitives.Add(new Sun());    // Assuming Sun implements IPrimitive