Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.
Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.
I've used this method successfully:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
You'll need to cast the returned object to your desired object type.
Probably my question should have been more specific. I actually know a base class for the string so solved it by:
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.
To create an instance of a class from another project in the solution, you can get the assembly indicated by the name of any class (for example BaseEntity) and create a new instance:
var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");