I am using a hierarchy of generic collection classes that derive from an abstract base class to store entity items that also derive from an abstract base class:
abstract class ItemBase { }
class MyItem : ItemBase
{
public MyItem()
{
}
}
abstract class CollectionBase<T> : Collection<T> where T : ItemBase, new() { }
class MyCollection : CollectionBase<MyItem> { }
The objectives of this model are to enforce strict type discipline on the members of any class derived from CollectionBase<T> and to guarantee that these members have a default public constructor. Thus far it works.
Now I want to create a factory method that returns an instance of a class derived from CollectionBase<T>. I understand that the usual approach would be:
public CollectionBase<T> CreateCollection<T>();
... or maybe ...
public T Create CreateCollection<T>();
However, the problem is that the calling routine does not know what "T" is required. It is the factory method itself that must determine the specific type of collection to return. So I need a non-generic method signature that says "the return type will derive from CollectionBase<T>". I envisage something like this (if it were legal) ...
public CollectionBase<> CreateCollection();
I assume this is another of those thorny generic variance issues, but even after reading Eric Lippert's extensive explanation on the subject, I am still unclear whether what I am trying to do is likely to be feasible in C# 4.0, and whether there is a simple workaround in C# 3.0.
Thanks in advance for your ideas.