views:

39

answers:

2

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;
        }
+4  A: 

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
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
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
A: 

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

http://stackoverflow.com/questions/840261/c-generic-new-constructor-problem

Prakash Kalakoti