Search code examples
c#genericsinterfacegeneric-list

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


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?


Solution

  • 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