views:

707

answers:

3

I have a bunch of MDI child nodes that are all created in the same way and to reduce redundant code I'd like to be able to call a method, pass it a string (name of child node), have it create the node and add it to the parent.

I can do all the stuff except create the class from a string of a class name, how can I do this?

A: 

If you have a string which is the name of the class, then you should be able to get a Type object therefrom, by calling Type.GetType(string). From that type, you should be able to use reflection to generate an object.

GWLlosa
+5  A: 

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;
BenAlabaster
All the classes extend Form. Care to explain what an assembly is?
Malfist
+3  A: 
Activator.CreateInstance(Type.GetType(typeName))
Bryan Watts