Fandi Susanto
Fandi Susanto

Reputation: 2453

C# ref Polymorphism workaround

I've made a function in C#:

private void customShow(Form someForm, Type formType) {
    if (someForm == null || someForm.IsDisposed) someForm = (Form)Activator.CreateInstance(formType);
    someForm.StartPosition = FormStartPosition.CenterScreen; 
    someForm.MdiParent = this;
    someForm.Show();
    someForm.WindowState = FormWindowState.Maximized;
}

And then I wanted to do this:

private void mnuKategori_Click(object sender, EventArgs e) {
    customShow(frmKategori, typeof(Master.FrmKategori));
    frmKategori.isCRUD = true;
}

It failed on the method's second line because the variable frmKategori is still null after the method execution. If I make the "someForm" argument into reference, it also fails because it seems C# doesn't support polymorphism with "ref" and "out" keyword. Does anybody have a suggestion on this? Thanks in advance for the reply.

Upvotes: 1

Views: 382

Answers (2)

Marksl
Marksl

Reputation: 822

Generics perhaps?

private void customShow<T>(ref T someForm) where T : Form, new()
{
    if (someForm == null || someForm.IsDisposed) someForm = new T();
    someForm.StartPosition = FormStartPosition.CenterScreen; 
    someForm.MdiParent = this;
    someForm.Show();
    someForm.WindowState = FormWindowState.Maximized;
}

And then I wanted to do this:

private void mnuKategori_Click(object sender, EventArgs e)
{
    customShow(ref frmKategori);
    frmKategori.isCRUD = true;
}

Upvotes: 5

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Why not simply have customShow return a new instance of Form, rather than fill in a ref/out parameter? There's really no reason to have a single out param with a void function.

Incidentally, I would also replace customShow with buildCustomForm, and save the actual Show() method for the very end. It can be confusing otherwise.

Upvotes: 2

Related Questions