I'm currently using this in one of my applications to new up a class
public static IMobileAdapter CreateAdapter(Type AdapterType)
{
return (IMobileAdapter)System.Activator.CreateInstance(AdapterType);
}
It's returning an instance of a class that implements IMobileAdapter, but you could use it equally easily with a string:
public static IMyClassInterface CreateClass(string MyClassType)
{
return (IMyClassInterface)System.Activator.CreateInstance(Type.GetType(MyClassType));
}
Call it using code similar to the following:
IMyClassInterface myInst = CreateClass("MyNamespace.MyClass, MyAssembly");
Of course, the class it creates must implement the interface IMyClassInterface in this case, but with a class factory, you'd likely have all your classes implementing the same interface anyway.
Edit:
In reference to your comment, for the purpose of this discussion, think of the term "assembly" as the set of files within your vb/cs project. I'm assuming that you're doing this all within a single project [assembly] and not spreading over multiple projects.
In your case as your classes will be extending the Form object, you would do something like this.
Form myInst = CreateClass("MyExtendedForm");
Or
Form myInst = CreateClass(Type.GetType("MyExtendedForm"));
Depending on whether you get the type within your CreateClass method or outside it. You would need to cast your instance to the correct type in order to access any custom members. Consider this:
class MyCustomForm : Form
{
public int myCustomField{ get; set; }
}
I've got a custom form that extends Form adding the myCustomField property. I want to instantiate this using Activator.CreateInstance():
public static Form CreateClass(string InstanceName)
{
return (Form)System.Activator.CreateInstance(Type.GetType(InstanceName));
}
I then call it using:
Form myInst = CreateClass("MyCustomForm");
So now I have my custom form stored in myInst. However, to access the custom property [myCustomField], you would need to cast your instance to the correct form:
int someVal = ((Type.GetType("MyCustomForm"))myInst).myCustomField;