0

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;
        }
Thunder
  • 10,366
  • 25
  • 84
  • 114

2 Answers2

5

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.

Jay
  • 56,361
  • 10
  • 99
  • 123
  • Thanks it solves specific problem.but just curious to know if we can pass the parameter to new() may be some thing like frm = new T("My Title"); – Thunder Jul 29 '10 at 05:35
  • You cannot set in the constraints that you want to have a constructor with a string parameter. The only way would be to call the constructor using reflection. – Xavier Poinas Jul 29 '10 at 09:31
1

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

Community
  • 1
  • 1
PSK
  • 17,547
  • 5
  • 32
  • 43