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 ..
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 ..
What about this?
public class MyList<T>: IList<T> where T: class
{
}
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
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>());
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.
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.