Reputation: 10986
HI, I have a generic function as shown below. It can be used to show a form by calling
showForm(ch);
IT works for the second function (new without parameter) ,But if I want to show form but with parameter in the constructor as in the third function (new with parameter) ,then I could not do it .Any one has an idea how to do it?
void showForm<T>(T frm) where T :Form, new()
{
if (frm == null)
{
frm = new T();
}
frm.MdiParent = this;
frm.Show();
}
//Works for this
public frmChild2()
{
InitializeComponent();
ChildToolStrip = toolStrip1;
// toolStrip1.Visible = false;
}
//Does not Work for this
public frmChild2(string title)
{
InitializeComponent();
ChildToolStrip = toolStrip1;
Text = title;
// toolStrip1.Visible = false;
}
Upvotes: 0
Views: 1434
Reputation: 17943
new()
guarantees that T will have a public constructor that takes no arguments - generally you use this constraint if you will need to create a new instance of the type. You can't directly pass anything to it.
Check this
Passing arguments to C# generic new() of templated type
Upvotes: 1
Reputation: 57919
using Where T : new()
tells the compiler that T
has a public
no-arg constructor.
The second form does not have such a constructor.
From what you show, there is no real need to set the title in the constructor (how would the showForm
method even know what to set?).
Since T
is also constrained to be a Form
you can set frm.Text =
after instantiating the Form
.
Upvotes: 5