Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through list of interfaces

Tags:

c#

I've got an interface with type T objects like so

public interface IService<T>

I've got a bunch of these interfaces with all different type T's. How can I add these interfaces into a List of some sort, iterate through the list and call a common method used by the interface. Any ideas? Is there an alternative approach?

If I add it to a list, I just can't see a way of casting the type T correctly.

like image 256
fes Avatar asked Jul 03 '12 09:07

fes


1 Answers

If the method is common, then presumably it doesn't depend on the T, so you should be able to do:

interface IService {
    void TheMethod();
}
interface IService<T> : IService {
    // other stuff
}

then have a List<IService>, and just:

foreach(var svc in list) svc.TheMethod();
like image 100
Marc Gravell Avatar answered Oct 03 '22 00:10

Marc Gravell