Possible Duplicate:
Casting an object to two interfaces at the same time, to call a generic method
I’m fairly sure you can’t do this so I’m wondering if there’s a workaround, but I need/want to cast an object to represent multiple interfaces for use with generic constraints. For example:
public void Foo<T>(T t) where T : IInterfaceA, IInterfaceB
{
}
If I have an object I want to say something like var t = (IInterfaceA | IInterfaceB)someObj; so I can pass t into this method.
Is there a nifty way of doing this? I’m using C# 3.5 so no dynamic available, but if it’s possible with dynamic please post it anyway.
EDIT
Despite the answer below, I would say the better solution is the one that most other answers point to. (This assumes that you can redefine the multiple classes that implement both interfaces.)
Create an interface that inherits from both InterfaceA and InterfaceB, then, for all classes that implement interfaces A and B, replace those interfaces with the new one. Before:
After:
The implementation of Foo is then fairly trivial. And, again, since you don’t know at compile time what type you have on hand, you may be able just to declare it as
END EDIT
You can do it using reflection, though some will say that this isn’t particularly “nifty”:
you could also do this, which could allow you to make Foo non-generic. It’s also fairly ugly, so I would hide this ugliness by making it private: