Trinidad
Trinidad

Reputation: 2816

Passing a generic definition of a collection as a type parameter - or how to use "List<>" as a type parameter

I'll try to be as straight-forward as possible.

I want to be able to do something like this:

var mylookup = new ModifiableLookup<MyClass, int, List<> >();
var myhashlookup = new ModifiableLookup<MyClass, int, HashSet<> >();

While having a generic class along this lines:

class ModifiableLookup<TKey, TElement, TElementCollection<> > : ILookup<TKey, TElement>
    where TElementCollection<> : ICollection<TElement>, new()
{
    private Dictionary<TKey, TElementCollection<TElement> > data;
    /// ... so on and so forth
}

But Alas, this does not work...

The work-around is to repeat the type parameter:

var mylookup = new ModifiableLookup<MyClass, int, List<int> >();
///...
class ModifiableLookup<TKey, TElement, TElementCollection> : ILookup<TKey, TElement>
    where TElementCollection : ICollection<TElement>, new()

Is there a way to accomplish something like this without repeating the collection element type parameter and without using reflection?

Upvotes: 1

Views: 210

Answers (1)

jason
jason

Reputation: 241641

No, it's not possible within your constraints. Open generic types can only appear as parameters to the typeof operator. They are not permitted anywhere else in your source.

Upvotes: 2

Related Questions