C# - how to create an inherited generic collection from a factory method?

ItemCollection isn't derived from CollectionBase() where TCollection : CollectionBase, new() where TItem : ItemBase { return new TCollection(); } Only the collection type needs a parameterless constructor. You'd call this with: var collection = CreateItemCollection().

ItemCollection isn't derived from CollectionBase, due to generic invariance. After all, you can add an ItemBase to a CollectionBase - but you don't want that for your ItemCollection! You need to make the method generic in two type parameters: static T CreateItemCollection() where TCollection : CollectionBase, new() where TItem : ItemBase { return new TCollection(); } Only the collection type needs a parameterless constructor.

You'd call this with: var collection = CreateItemCollection().

Thanks. This solves my problem, even if I still can't fully understand why the compiler insists on being so strict (as commented by JaredPar below). – Tim Coulter Sep 8 '09 at 15:32 1 @Tim: As I said, because ItemCollection must not allow all the same calls as CollectionBase.

Read up on Eric Lippert's blog series about variance for more details - unfortunately I need to run now, so don't have time to chase the link. – Jon Skeet Sep 8 '09 at 15:33.

The problem here is generic constraints, in C# 3.0, have any leeway with regards to variance. The matching is instead fairly strict. Since ItemCollection derives from CollectionBase it is not considered to be derived from CollectionBase even though the types may appear to be compatible.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions