Question

OK, I've searched and saw some questions on how to create a class using its name. My question is not quite the same, so I'm going to ask it anyway.

My application has 2 classes, say, "A" and "B". In another class, I need to use these two classes (the third class is called by an external service). The external service only passes me the names of the two "A" and "B" classes as string. In the third class, I know I can do something like:

case "A":
    create an instance of A
case "B":
    create an instance of B

but that seems weird. I'd like to do it dynamically so I was thinking of doing Activator.CreateInstance but not sure if it's good programming because it seems "CreateInstance" is used when you load an assembly remotely. In my case, everything is in one project.

Any advice? Thank you so much!

Was it helpful?

Solution

This is perfect case for using Factory Method pattern.

http://www.dofactory.com/Patterns/PatternFactory.aspx

OTHER TIPS

If number of classes that you want to create by their name is limited (such as 2 different classes in your example), I would prefer the way with "switch"

public object ClassFactory(string ClassName)
{
    switch(ClassName)
    {
        case "A": return new A();
        case "B": return new B();
    }
}

because it is both faster and safer (if name of class comes from external service, imagine what would happen, if this service sends malicious class name).

Otherwise Activator.CreateInstance should not make any problem, but make sure, you thoroughly verify input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top