Using Reflection to open a form by name

Here is a quick example of how the System.Reflection namespace can be utilised to open form instances in a method that accepts the form name as a string. It also shows how you can pass across variables to forms with overloaded constructors.

It’s particularly useful when working with a main menu structure, such as I have in a current project loaded into a Treeview.


private void LoadNewForm(string formName)
{
    try
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        Type type = assembly.GetType(formName);

        //for this form I have an overloaded constructor, accepting a 'User' object
        ConstructorInfo ci = type.GetConstructor(new Type[1] { typeof(User) }); 
        object[] argVals = new object[] { CurrentUser };  //pass 'CurrentUser' variable to form constructor
        Form frm = (Form)ci.Invoke(argVals);

        frm.Show();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}