how can I add an IMyType<SubTypeImplementation>
to this list?
IMyType
needs to be covariant for this to work. Being covariant means that the generic type can only be included in the output of functions. Since your interface includes an EventHandler
that takes the generic type as part of the input, your interface cannot be covariant.
Let's change you interface names to understand why. Suppose you run a zoo and want to distinguish "view-only" cages from "normal" cages. So you have two interfaces:
IViewOnlyCage<out T>
{
public T View();
}
ICage<T>
{
public Add(T animal);
}
Now consider two "lists" of cages:
List<IViewOnlyCage<IAnimal>> list1;
List<ICage<IAnimal>> list2;
And I populate the lists as such:
list1.Add(new Cage<Tiger>());
list1.Add(new Cage<Deer>());
In the first case, a list of view-only cages is perfectly reasonable. Each cage contains some type of animal, so there's no danger of the two animals ending up together.
But consider the second - with an Add
method I could do this:
list2.Add(new Cage<Tiger>());
ICage<IAnimal> cage = list2[0]; // a reference to the tiger cage
cage.Add(new Deer()); //uh-oh... bad news for the deer
Since your interface contains indirect inputs, something like this would be possible:
List<IMyType<IMySubType>> list = new List<IMyType<IMySubType>>();
list.Add(new IMyType<SubTypeImplementation>());
IMyType<IMySubType> item = list[0]; // seems OK
item.OnSomething += new EventHandler(IMyType<SecondSubType>, EventArgs<SecondSubType>);
but the actual generic type is SubTypeImplementation
, not SecondSubType
, so you have a type conflict.
The easiest changes seems to be to move the event handler to a different interface. You can then make IMyType
covariant and have a List<IMyType<IMySubType>>
.