0

Possible Duplicate:
c# create an instance of a class from a string

Hopefully this is pretty straightforward.

I'm looking to dynamically call an object based off a string representation of its name. Here is an example of what I'm looking to do:

public class Class1
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
    public string Property3 { get; set; }
}

public class Class2
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
    public string Property3 { get; set; }
}

My goal is to call Class2 from a string representation (the GetClassFromString() is obviously made up, but hopefully describes what I'm looking to do):

Object cls = Object.GetClassFromString("Class2");

Then cls would be an object from Class2.

Community
  • 1
  • 1
BenR
  • 2,791
  • 3
  • 26
  • 36
  • `if (str == "Class2") return new Class2();`? – dtb Sep 09 '12 at 23:19
  • DTB, that does seem practical. Thank you. However, if I am working with something that could be calling 40+ classes dynamically. I would like to avoid having to add a new if condition for every new class that might be added in the future. Would you have any suggestion on a more dynamic way of doing it? – BenR Sep 09 '12 at 23:22
  • @BenRecord: Check out the question I linked to: http://stackoverflow.com/questions/223952/c-sharp-create-an-instance-of-a-class-from-a-string (yours is a duplicate of this one). That's a good solution, though a better solution is probably refactoring your application so you don't need reflection, unless you have some kind of exotic design. – Chris Laplante Sep 09 '12 at 23:24
  • `Activator.CreateInstance` is what you're looking for (though be careful, you'll have to use the fully qualified name o the class Class2 can exist in different namespaces and different assemblies loaded in the appdomain. That being said, I should warn that doing this is almost certainly a bad idea. I've written apps that were dynamic to high-heaven before without having even once to rely on this. – George Mauer Sep 09 '12 at 23:25

1 Answers1

1

Have a look at the Activator.CreateInstance method.

dowhilefor
  • 10,971
  • 3
  • 28
  • 45