Converting a method to generic for reuse with Forms

I'm working on a statistical add-in for Excel and the method below is implemented for each plot I have to draw. I have about 10 different plots and each time only the Type of the Form changes.

private void ShowBoxWhiskerPlotForm()
{
    // Check if the Form already exists. Create it if not.
    if (_boxWhiskerPlotForm == null || _boxWhiskerPlotForm.IsDisposed)
        _boxWhiskerPlotForm = new Forms.BoxWhiskerPlotForm();

    // Check if the Form is already visible.
    if (_boxWhiskerPlotForm.Visible == false)
        // Show the Form if it isn't.
        _boxWhiskerPlotForm.Show(
            new WindowImplementation(new IntPtr(Globals.ThisAddIn.Application.Windows[1].Hwnd)));
    else
        // Refresh if it is.
        _boxWhiskerPlotForm.Refresh();

    // Bring the Form to the front.
    _boxWhiskerPlotForm.BringToFront();
}

Is there a way to make this method generic? Something like the code below but without the hard call to form = new Forms.BoxWhiskerPlotForm();. The problem here is that it can't convert the type of T which will be something like public class BoxWhiskerPlotForm : Form to the BaseType Form.

private void ShowForm<T>(Form form)
{
    // Check if the Form already exists. Create it if not.
    if (form == null || form.IsDisposed)
        form = Activator.CreateInstance<T>();

    // Check if the Form is already visible.
    if (form.Visible == false)
        // Show the Form if it isn't.
        form.Show(
            new WindowImplementation(new IntPtr(Globals.ThisAddIn.Application.Windows[1].Hwnd)));
    else
        // Refresh if it is.
        form.Refresh();

    // Bring the Form to the front.
    form.BringToFront();
}
Jon Skeet
people
quotationmark

You just need to constrain T with a class type constraint. You can also add a new() constraint to make the code simpler:

private void ShowForm<T>(T form) where T : Form, new()
{
    // Check if the Form already exists. Create it if not.
    if (form == null || form.IsDisposed)
    {
        form = new T();
    }
}

people

See more on this question at Stackoverflow