views:

67

answers:

2

Here is the scenario. I have a bunch of UserControls that all inherit from MyBaseControl. I would like to instantiate a UserControl based on its name. For instance:

void foo(string NameOfControl) {
    MyBaseControl ctl = null;        
    ctl = CreateObject(NameOfControl);  // I am making stuff up here, 
                                        // CreateObject does not exist
}

How do i instantiate this UserControl based on its name. I could have a gigantic switch statement and that smells bad. All the UserControls, including their Base class, are in the same project and all have the same namespace.

+1  A: 

The best way to do this would be to load the type via reflection. Since they are all in the same assembly/namespace, you can do this. Otherwise, you'd have to load the assembly separately. Also, it assumes an empty constructor.

MyBaseControl ctl = null;
ctl = (MyBaseControl) typeof(MyBaseControl).assembly.GetType(NameOfControl).GetConstructor(new Type[0]).Invoke(new object[0]);

If the constructor isn't an empty one, change the type/object arrays.

Erich
Does not work, I am getting Object reference not set to an instance of an object.
AngryHacker
It is the right solution. Find out what part of the expression is null by breaking it apart. Assembly.GetType() is the probable null, make sure you pass the namespace name as well.
Hans Passant
The Null Ref can only happen in 1 of two places: The `GetType` or the `GetConstructor`. If your NameOfControl variable isn't correct (requires the full namespace) it won't work, or if you don't have a publicly available empty constructor, it won't work.
Erich
Yes, namespace was missing.
AngryHacker
+1  A: 
    void foo(string NameOfControl)
    {
        MyBaseControl ctl = null;
        ctl = (MyBaseControl) Assembly.GetExecutingAssembly().CreateInstance(typeof(MyBaseControl).Namespace + "." + NameOfControl);
    }

Above assumes that each of your derived control class as a default parameter-less constructor.

logicnp