class B : A {}
class Sub<T> where T:A
{
//...
}
I want to store Sub instances in a collection.
var c = new List<Sub<A>>();
c.Add(new Sub<B>()); //doesn't work
However, to get it to actually work, I have to declare an interface and store instances of that interface.
interface IBase
{
void DoStuff(A a);
}
var c = new List<IBase>();
c.Add(new Sub<B>()); //works
Is there a more elegant way of doing this?
No. Instantiations of a generic type with different type arguments are completely unrelated. The only way you can get them in the same list is by having the list use a common non-generic base class or interface, as you did here.
You can achieve an approximation of what you want by using a covariant generic interface:
Which can be used as follows:
You need an interface because only interfaces can have covariant or contravariant type parameters.