tags:

views:

123

answers:

3

Is it possible to inject an interface into an existing 3rd party class that I can not alter? Like extension methods but for an interface (and its implementation for the class that it had been injected to).

I like to optionally use one of two similar 3rd party libraries by giving classes that are similar in both libraries the same interfaces. So that I do not have to convert there classes into mine.

+1  A: 

As long as you're dealing with interfaces, why not just go with wrapping the classes in your own classes, that implement the interfaces?

Lasse V. Karlsen
+3  A: 

I don't completely understand what you mean about injecting an interface, but you could use the Adapter pattern to achieve this. See also: http://dofactory.com/Patterns/PatternAdapter.aspx

Create your own interface, then create your own classes that implement the interface, which contain/wrap the 3rd party classes.

Andy White
A: 

You should look at the Decorator Pattern which allows you to extend a class by composition.

e.g. Given sealed class A which implements InterfaceA:

public interface InterfaceA
{
    int A {get; set;}
}

public sealed Class A : InterfaceA
{
    public int A {get;set;}
}

You could extend InterfaceA and then use a decorator class B to encapsulate an instance of class A and provide additional methods.

public interface MyExtendedInterfaceA : InterfaceA
{
    int B {get;set}
}

public class B : MyExtendedInterfaceA
{
    private InterfaceA _implementsA = new A();

    public int A
    {
        get
        {
            return _implementsA.A;
        }
        set
        {
            _implementsA.A = value;
        }
    }

    public int B {get; set;}
}

Alternatively, decorator Class C could add a whole new interface:

public interface InterfaceC
{
   int MethodC();
}

public class C : InterfaceA, InterfaceC
{
private InterfaceA _implementsA = new A();

    public int A
    {
        get
        {
            return _implementsA.A;
        }
        set
        {
            _implementsA.A = value;
        }
    }

    public int MethodC()
    {
        return A * 10;
    }
}
Dr Herbie
It looks like you did not read my question carefully. If class A is one of the 3rd party library classes it would be impossible for me to add InterfaceA.
Martin
It looks like you mis-interpreted what I meant; I was outlining the class A structure which could either be in your own code or the 3rd party library. Either way, it's sealed and you cannot change it.Classes B and C are the code that you write in your own class.
Dr Herbie