Suppose I have a bunch of objects A, B, C, ... that implement multiple interfaces I1, I2, I3, ...
My objective is to have functions like these
public void AddObjectThatImplements<T>(T o){
//add o to some data structure that stores objects that implement T
}
public List<T> GetInterfaces<T>(){
//return all T instances from the list of who implements T
}
In the initialization method of each of these objects, I can add their interfaces into a any kind of data structure that can help making these functions work.
For simplicity, all interfaces I1, I2, ... inherit from a base interface I0.
How can I build such functions? Any additional data structure is welcome.
You can store all your objects in a
List<I0>.Then in
GetInterfacesuse the is operator, to build a new list of all objects in the first one that areis T.From the documentation, the
isoperator istruein particular when:I am aware that it ignores
TinAddObjectThatImplementsbut it seems to implement the behavior you need.Therefore in the example below I renamed
AddObjectThatImplementsto simplyAddObject:Update:
As commented below,
GetInterfacescan be implemented more elegantly using LINQ (requiresusing System.Linq;) - keeping the same behavior: