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:
[source:c#]CreateForm( typeof(CustomFormType) );
Form CreateForm( Type formType )
{
return (Form)Activator.CreateInstance(formType);
}
[/source]
Tags: C#, polymorphism, programming
[…] 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#; […]