You cannot do the...
ItemCollection<Feature> features = ...;
ItemCollection<Item> items = features;
It's about generics variance
(covariance and contravariance that is) - and it's only supported for interfaces, delegates - and only providing they're designed that way (decorated with in
/ out
- and conforming to the rules that go with it). e.g. IEnumerable<>
is (if you lookup its definition you'll see the out
). For more details I think it's best to read more...
How is Generic Covariance & Contra-variance Implemented in C# 4.0?
Understanding Covariant and Contravariant interfaces in C#
http://msdn.microsoft.com/en-us/library/dd799517.aspx
In your case, you could design an IItemCollection<out T>
(interface
) - that (theoretically) might support the casting you need. But it'd have to be read-only
(a tad simplified and not entirely correct but it's easier to think that way - the rules are a bit more complex).
Since you're naming it a 'collection' I'm assuming it's not just for enumerating, viewing the items - i.e. if you have an Add
of a sort (which requires input parameters
- i.e. contra-variance
) that clashes with the 'covariance' you need for the upcasting
. Also any other parameters involved might not allow your interface to be made covariant.
Also some other posts I made related...
How to make generic class that contains a Set of only its own type or subtypes as Children?