I have a problem with declaring a type as passed from parameter type variable.
public static void ShowThisForm(Type passXtraForm, Form parent)
{
var xfrm = passXtraForm.GetType();
xfrm xfrmName = new xfrm();
xfrmName.Show();
}
Can I declare a variable as a type from passXtraForm.GetType() and declare it to another variable? Just passing the type of form to another class.
Thanks in advance for the response.
First of all, it doesn’t look like you need the
parentparameter; I’d eliminate it entirely. Then I’d use generics to do what you’re trying to accomplish:The
where T : Form, new()portion of this code is called a type constraint and it prevents you from calling theShowThisFormmethod with a type that doesn’t have a default constructor and derive fromForm.By indicating that
Tmust have a default constructor, the compiler knows how to resolvenew T(); by indicating thatTderives fromForm, the compiler knows how to call the.Show()method.So, if you have a form class called
MyForm, you could use the following syntax to call this method:For more documentation, you should take a look at these articles on MSDN: