0

I´m trying to create and show forms in VS 2013 with a generic method this is my method:

void showOrUpdateForm<T>(ref Form form) where T : Form 
{
    if (form == null)
    {
        form = Activator.CreateInstance(typeof(T)) as T;
        form.Show();
    }
    else
        form.WindowState = FormWindowState.Normal;

    form.Focus();
}

this code i got it from here. So when i try to call this method like they told like that:

 myForm1 form;
 showOrUpdateForm<myForm1>(ref form);

It give me error:

Error 1 The best overloaded method match for 'GestionEAS.GestionEAS.showOrUpdateForm(ref System.Windows.Forms.Form)' has some invalid arguments

Error 2 Argument 1: cannot convert from 'ref package.Views.form' to 'ref System.Windows.Forms.Form'

How can I fix this?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
BHimura
  • 13
  • 2
  • side note: the `myForm1 form;` fragment is incorrect, since `form` contains *thrash*, not *null*; change it into `myForm1 form = null;` – Dmitry Bychenko Apr 01 '15 at 14:52
  • "showOrUpdateForm(ref Form form)" - Just a hint: there is no need to have the 'ref'. More info here: http://stackoverflow.com/questions/635915/when-to-use-ref-and-when-it-is-not-necessary-in-c-sharp – Ulric Apr 01 '15 at 14:58
  • Dmitry: its not a prb if I change it to myForm1 form = null; it gives me the same error. – BHimura Apr 01 '15 at 15:03
  • thnx for the Hint Ulric ^-^ – BHimura Apr 01 '15 at 15:03

3 Answers3

1

You can't pass a myForm1 as a ref Form.
You should change that to a ref T, so that the parameter type matches the variable.

Also, you should add , new() to your generic constraints and replace Activator.CreateInstance(typeof(T)) as T with new T()

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Seems, that you want something like that:

// I'd rather return potentially created form directly (not via "ref")
// do you need "this" in the method? That's why "static"
static T showOrUpdateForm<T>(T form = null)
  where T: Form, new() {

  if (null == form) 
    form = new T(); // <- no Activator since "new()" constraint is declared

  form.WindowState = FormWindowState.Normal;
  form.BringToFront(); // <- if the form is not a foreground one

  if (form.CanFocus) // <- better check than have an exception
    form.Focus();

  return form;
}
...
// more compact and readable
myForm1 form = showOrUpdateForm<myForm1>();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

How about this, will nicely cater for creating forms with different parameters

void showOrUpdateForm<T>(ref T form, Func<T> formCreator) where T : Form 
{
    if (form == null)
    {
        form = formCreator();
        form.Show();
    }
    else
        form.WindowState = FormWindowState.Normal;
    if(form.CanFocus)
        form.Focus();
}

using it as . . .

MyForm myForm = null;
form1 = showOrUpdateForm(myForm, () => new MyForm());
Binary Worrier
  • 50,774
  • 20
  • 136
  • 184