Ucodia
Ucodia

Reputation: 7720

What is the most elegant way to use generic type as generic parameter?

I was wondering if there was a more elegant way than this example to use generic type as generic parameter:

public class Wrapper<TObject>
    where TObject : MyBaseClass
{
}

public class WrapperCollection<TWrapper, TObject> : Collection<TWrapper>
    where TWrapper : Wrapper<TObject>
    where TObject : MyBaseClass
{
}

Actually, if I want to initialize an instance of WrapperCollection I would to do it like this:

WrapperCollection<Wrapper<MyClass>, MyClass> collection = 
            new WrapperCollection<Wrapper<MyClass>, MyClass>();

And as I am not really happy with that, what would be really elegant would be to be able to initialize it like that:

WrapperCollection<Wrapper<MyClass>> collection = 
            new WrapperCollection<Wrapper<MyClass>>();

So my question is simple: is there a way to do that or is there a more elegant design to use for my CollectionWrapper?

Thanks.

Upvotes: 2

Views: 123

Answers (1)

Dean Harding
Dean Harding

Reputation: 72668

If WrapperCollection<T> always contains a collection of Wrapper<T>s, then you can do this:

public class WrapperCollection<TObject> : Collection<Wrapper<TObject>>
    where TObject : MyBaseClass
{
}

...

WrapperCollection<MyClass> collection = new WrapperCollection<MyClass>();

Upvotes: 1

Related Questions