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?
Then you should be able to have
John is correct.
Might I also suggest (if you are using C# 4) that you make your interface covariant?
This could save you some trouble later when you need to get things out of the list.
You say it won't work because you don't define
T
. So define it: