Lac Ho
Lac Ho

Reputation: 227

Programming advice on creating a class using class name

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!

Upvotes: 1

Views: 115

Answers (2)

Firoz Ansari
Firoz Ansari

Reputation: 2515

This is perfect case for using Factory Method pattern.

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

Upvotes: 1

Ňuf
Ňuf

Reputation: 6207

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.

Upvotes: 2

Related Questions