Common interface for two third-party classes I don't control. External Polymorphism?

Try this approach:

public interface IEmployeeAdapter
{
    string Age { get; set; }
    string Name { get; set; }
}

class EmployeeTypeAAdapter : TypeA, IEmployeeAdapter
{
    public EmployeeTypeAAdapter(TypeA employee) { }
}

class EmployeeTypeBAdapter : TypeB, IEmployeeAdapter
{
    public EmployeeTypeBAdapter(TypeB employee) { }
}

public static class EmployeeAdapterFactory
{
    public static IEmployeeAdapter CreateAdapter(object employee, EmployeeType type)
    {
        switch (type)
        {
            case EmployeeType.TypeA: return new EmployeeTypeAAdapter((TypeA)employee);
            case EmployeeType.TypeB: return new EmployeeTypeBAdapter((TypeB)employee);
        }
    }

    // or without enum

    public static IEmployeeAdapter CreateAdapter(object employee)
    {
        if (employee is TypeA) return new EmployeeTypeAAdapter((TypeA)employee);
        if (employee is TypeB) return new EmployeeTypeABdapter((TypeB)employee);
    }

    // or better introduce sort of type map
}

Another proper name is EmployeeProxy, as you prefer.


What you're trying to do is known as Duck typing. You can do this using adapter classes and a shared interface, but creating these adapters manually requires a lot of repetitive glue code. One way you can get around writing the glue code is to construct the adapter type dynamically. You can do this yourself via IL Emit (a worthwhile exercise if you've never had a chance to play with it before, though there can be quite a few boundary cases to consider.) If you're just interested in getting it working, however, you might check out this project as a place to start. The C# 'dynamic' type could also be used (and winds up doing some of the same code generation behind the scenes), but it doesn't give you a reference you can pass around to non-dynamic code as if it were an interface type.