Search code examples
c#createinstance

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!


Solution

  • This is perfect case for using Factory Method pattern.

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