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.
if (str == "Class2") return new Class2();?Activator.CreateInstanceis 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.