Let's say you have a third party DLL that contains a class...
class ThirdPartyClass { public bool Foo { get { return true;} } }
And you want to create your own class that has a method or property in common with the third party class:
class MyClass { public bool Foo { get { return true;} } }
As you mention, what you'd normally do is add an interface to the third party class, and then implement that interface in your own class. But you can't do that, as you also pointed out. And without an interface in common, you're stuck with that clunky if/then construct.
If I correctly understand your situation, you can deal with it as follow. Extend the third party class to add the interface, like so:
interface IMyInterface { bool Foo { get; } } class MyThirdPartyClass : ThirdPartyClass, IMyInterface { }
Since Foo is public, it will get inherited and be available, and satisfy the interface. And now you can create your own class too:
class MyClass : IMyInterface { public bool Foo { get { return true; }} }
And you can use them interchangeably:
IMyInterface a = new MyThirdPartyClass(); IMyInterface b = new MyClass(); bool c = a.Foo; bool d = b.Foo;
That's how I would do it.
You may run into a problem if the third party class is sealed. If that is the case, you have to wrap it instead of inheriting from it:
class MyThirdPartyClassWrapper : IMyInterface { private readonly ThirdPartyClass _wrappedInstance = new ThirdPartyClass(); public bool Foo { get { return _wrappedInstance.Foo; } } }
And then it'll still work:
IMyInterface a = new MyThirdPartyClassWrapper(); IMyInterface b = new MyClass(); bool c = a.Foo; bool d = b.Foo;