I use this code to load a MDIchild form from within another MDIchild form. I’m learning still how to use generics in my method so when I get my method to work finally with the help of the people here I end u with two slightly different codes which in my case do the job the same way. So my question is – is it coincidence that those two variations do the same job or there’s just no difference between the two approaches.
So here is version 1:
protected void LoadAForm<T>(ref T sendTo) where T : Form
{
MainForm frm = this.MdiParent as MainForm;
if (frm != null)
{
sendTo = SingletonFormProvider.GetInstance<T>(frm, true);
sendTo.MdiParent = frm;
sendTo.Dock = DockStyle.Fill;
sendTo.Show();
}
}
And here is version 2:
protected void LoadAForm<T>(ref T sendTo) where T : Form
{
MainForm frm = this.MdiParent as MainForm;
T temp;
if (frm != null)
{
temp= SingletonFormProvider.GetInstance<T>(frm, true);
temp.MdiParent = frm;
temp.Dock = DockStyle.Fill;
temp.Show();
}
}
So is there (if any difference) to use the T temp instantiation or it’s just the same thing?
The main difference is that in the 2nd scenario, your newly created and shown form will not be available outside LoadAForm in your sendTo param.
The first method seems to work correctly, accomplishing what it was intended for by passing a reference parameter to it.
Another natural way is to return the newly created as a function return value form instead of returning it throug a ref’ed parameter.
LATER EDIT:
Frankly said, as Henk Holterman said, you are misusing the ref usage.
By the way, if you still want to pass a parameter to that method, use out instead of ref!
Ok, this is what I mean: declare your method like this:
and return the form you just instantiated. Simple.