views:

56

answers:

1

Hi,

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.

+1  A: 

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>();
Dean Harding
Looks like `TWrapper` can also be any class derived from `Wrapper`. In C++ this is easy (use typedef), in C# not so much.
Ben Voigt
@Ben: Ah yes, you may be right...
Dean Harding
Quite interesting in a syntax way but not really relevant of the real object. By doing this the user would thing he is creating a collection of TObject, which is not the case. Thank you.
Ucodia