Reputation: 808
Let s assume that i have a string named str with some value that is the name of a class.
e.g string str="MyClass";
Is it any way to instatiate an object or a list of objects using this variable?
( That's because I don't know from the beginning what type of objects i should create but somewhere inside the program I get a list of strings with the name of the classes )
Some dummy silly code of what i really want is :
List<**str**> myList = new List<str>();
or
**str** object = new **str**();
Thanx in advance!
Upvotes: 0
Views: 141
Reputation: 7846
You could base your code on the following, which constructs an instance of MyClass given its name:
namespace MyNameSpace {
public class MyClass {
public MyClass() {
// initialise
}
public static MyClass CreateMyClassFromName() {
Type myType = Type.GetType("MyNameSpace.MyClass");
System.Reflection.ConstructorInfo constinfo = myType.GetConstructor(new Type[] { });
MyClass mc = (MyClass)constinfo.Invoke(null);
return mc;
}
}
}
Upvotes: 0
Reputation: 75306
You can use reflection, assume your class is in the same assembly:
string input = "MyClass";
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == input);
MyClass myObject = (MyClass)Activator.CreateInstance(type);
Upvotes: 1