Always Get Better

C#: Instantiating a class of Unknown Type

The project I am currently working on has several dozen different types of Form classes, each of which is accessible from a common menu strip. Rather than repeatedly instantiating each of the forms from the menu item handlers, I wanted to funnel the request to a single function.

The problem is: How do you instantiate a form when the type is unknown?

The code snippet is:

CreateForm( typeof(CustomFormType) );

Form CreateForm( Type formType )
return (Form)Activator.CreateInstance(formType);

Tags: , ,

One Response to “C#: Instantiating a class of Unknown Type”

  1. […] April saw a return to writing about useful tech tips and obscure programming knowledge. I also wrote the blog’s most popular article to date about methods for closing forms in C#; […]

Leave a Reply