So I have an object, lets say Item<U>. I want to create a(n) (I)List<T> containing a collection of these items. The problem that I am running into is that the collection of Item<U> can have any number of different types for U in them.
What I can not figure out is the signature to use for the IList. I tryed IList<Item<T>>, but because I do not (in the class where the IList is to be used) have a defination of T (which as I said varys anyhow) I can not use this signature. What is the best way to approach this requirement?
You need to add a non-generic interface to your
Item<U>and make the collection out of those interfaces.There is no way you can create a collection of
IList<Item<T>>where T is some base type for a lot of different object types you want to place into the same list. This is co(ntra)-variance in place which specifically prohibits this.So you need to instead add something common, that isn’t generic, and make the list out of that. For instance, you might make
Item<T>implementIItem, and createIList<IItem>instead.That’s the best you can do.