Basically I have a list of objects where each object might implement a different set of interfaces:
List<BaseObject> objects;
class BaseObject
{
public void DoStuff();
}
interface IX
{
void DoX();
}
interface IY
{
void DoY();
}
interface IZ
{
void DoZ();
}
And i would like to write something like this:
foreach(var obj in objects.OfType<BaseObject and IX>)
{
obj.DoStuff();
obj.DoX();
}
(E.g. i perform a specific algorithm for objects of type BaseObject and IX without having to do typecasts there)
Is it possible to do in C#?
What’s the most elegant solution?
I can do this:
foreach(var obj in objects.OfType<IX>)
{
var baseobj = (BaseObject)obj.DoStuff();
obj.DoX();
}
But i find it ugly.
And I might need to apply specific operations to types that implement say interface IX and interface IZ.
foreach(var obj in objects.OfType<BaseType and IX and IZ>)
{
obj.DoStuff();
obj.DoX();
obj.DoZ();
}
One possible way is to use
dynamic:Of course, you can still cast if you don’t want to use
dynamic: