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.

4
  • if (str == "Class2") return new Class2();? Commented Sep 9, 2012 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? Commented Sep 9, 2012 at 23:22
  • @BenRecord: Check out the question I linked to: stackoverflow.com/questions/223952/… (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. Commented Sep 9, 2012 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. Commented Sep 9, 2012 at 23:25

1 Answer 1

1

Have a look at the Activator.CreateInstance method.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.