public IList GetClientsByListofID(IList ids) where T : IClient { IList clients = new List(); clients.Add( new Client(3)); }
I am getting a compiler error here:
cannot convert from 'Bailey.Objects.Client' to 'T'
The client object implements the IClient interface. My goal here is to try and loosen the coupling between my classes (learning DI stuff atm). I was thinking that I can say it can use any type of client object and that would be returned.
Am I completely off base here?
Thanks
Jon Hawkins
You cannot use generic constraints in this way. How can the compiler guarantee that the type parameter is a Client
simply because it implements the IClient
interface? Couldn't many types implement that interface?
In this case (that is in the case where you need to work with the type, not the interface) it is better to constrain the type parameter with the type itself like this:
public IList<T> GetClientsByListofID<T>(IList<int> ids) where T : Client
{
IList<T> clients = new List<T>();
clients.Add(new Client(3));
// ...
}
and once doing that I am wondering if you need a generic method at all:
public IList<Client> GetClientsByListofID(IList<int> ids)
{
IList<Client> clients = new List<Client>();
clients.Add(new Client(3));
// ...
}