tags:

views:

172

answers:

6

Hello there..

I need to create a generic IList where T would be a generic class with various interfaces. For example ChannelFactory<IService1> or ChannelFactory<IService2> and etc ..

+1  A: 

What about this?

public class MyList<T>: IList<T> where T: class
{
}
Ngu Soon Hui
+4  A: 

Then do it!

Nobody will hinder you!

Where is your problem?

winSharp93
Comments. They're all the rage.
Kobi
+1 for your style
BlueTrin
+7  A: 

If you want this you should change your design if necessary. Make all interfaces derive from the same interface, for example IServiceBase. You can then use the following constraint on your generic class:

IList<T> where T: IServiceBase
Gerrie Schenck
An interface hierarchy is the way to go for sure.
Codesleuth
+1  A: 

You could do:

IList<ChannelFactory<IService1>> list = new List<ChannelFactory<IService1>>;

But you can't mix and match ChannelFactory< IService1 > and ChannelFactory< IService2 > object in this list.

If you really need to mix and match in the list use a non generic one:

IList non_generic_list = new List();
non_generic_list.Add(new ChannelFactory<IService1>());
non_generic_list.Add(new ChannelFactory<IService2>());
Paolo
A: 

You can just do this:

var list = new List<ChannelFactory<IService1>>();

In fact, you can nest generics as much as you want, but you may get tired of all the angle brackets after a while.

Mark Seemann
+1  A: 

If you need to create lists from dynamic types during runtime, you can create generic list types like this.

public IList CreateList(Type interfaceType)
        {
            return (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(interfaceType));
        }

Then you can just do:

IList<ChannelFactory<IService1>> list = CreateList(typeof(ChannelFactory<IService1>)) as IList<ChannelFactory<IService1>>;

If you have knowledge of which generic class you need when and where, go for the interface hierarchy. If you don't have full control over this, but need to create lists dynamically during runtime, this could be a solution.

Terje