Reputation: 1318
I have 12 classes in my project like this:
class class1
{
}
class class2
{
}
in another class I have a method that I want to create an instance of class1
or class2
according to a string:
public void MyMethod(string s)
{
//I want to create an instance of class1 if s=="class1" or class2 if s=="class2"
}
How I can do this?
Upvotes: 0
Views: 101
Reputation: 1737
Here is a work around try this hope it will work.
First you need to pass class actual name in string, e.g if you have a class ClassA
then Pass ClassA
to this one it will create an instance of the class.
private object MyMethod(string className)
{
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetTypes()
.First(t => t.Name == className);
return Activator.CreateInstance(type);
}
Upvotes: 2