High Plains Grifter
High Plains Grifter

Reputation: 1571

Choose Implementation of Interface by Variable

In my GUI there is a drop down list of customers. Each customer has a class associated with it, containing the methods associated with that customer (for instance loading their invoice format etc). Each of the customer classes implements the interface "ICustomer", but the contents of the methods differ.

The calling class has an ICustomer property - I would like to set that to be the class represented by the selected value in the dropdown. Something a bit like this pseudocode:

public interface ICustomer
{
    int GetInvoice();
}

and

Class Caller()
{
    public ICustomer Customer { get; set; }
    public void Choose(string customerName)
    {
        Customer = //??? ["Get class where name == customerName"];
        var foo = Customer.GetInvoice();
    }
}

From my very limited understanding and muddled internet searching, I think I need to use reflection to achieve this, but I have so far failed to return a specific, set-at-runtime class from the interface. How would I go about achieving this?

Upvotes: 0

Views: 84

Answers (1)

V0ldek
V0ldek

Reputation: 10563

var type = Type.GetType(customerName);
ICustomer customer = (ICustomer)Activator.CreateInstance(type);
var invoice = customer.GetInvoice();

Note that the customerName has to be a namespace-qualified name. So if you're holding all your user classes are in the X.Y.Z namespace you have to get type "X.Y.Z." + customerName.

Upvotes: 1

Related Questions