I am creating a MDI form and I have a method that loads the different forms. Now I need to make a little modification – I need to add functionality that calls one child form from within another child form.
Because I need this in several different places I made a new class from who all the classes that need this functionality inherits. I want to make it work with generic types so I can pass every form class that I may need like LoadAForm(MyForm1) or LoadAForm(MyForm2) and so on.. I hope I it’s clear what I want as final result.
I tried this:
protected void LoadAForm<T>(ref T sender)
{
MainForm frm = this.MdiParent as MainForm;
T temp;
if (frm != null)
{
sender = SingletonFormProvider.GetInstance<temp>(frm, true);
sender.MdiParent = frm;
sender.Dock = DockStyle.Fill;
sender.Show();
}
}
which doesn’t work. But I have almost no experience with generics even more when they are used in methods, so I don’t know how to go on.
What I get as an error using this syntax is The type or namespace "temp" could not be found...". I'm not even sure that this is the way to do it.GetInstance<>` has to take an argument of the same type as the type of the form I’m calling.
You need to use the type parameter, not the variable name:
Also, to ensure that
Tis valid (as your comment suggests) you will need to constrain it: