Blog: Time to reflect

Dispose Modal WinForm Dialogs

Added by Fons Sonnemans on 12-Dec-2004

There is a difference in disposing Modal and Non-Modal forms. In a training I gave last week I noticed that even experienced developers didn't know that Modal Dialogs don't dispose automatically, Non-Modal do.

private void buttonShowNonModalForm(object sender, System.EventArgs e) {
    new TestForm().Show();
}

private void buttonShowModalDialog(object sender, System.EventArgs e) {
    new Form2().ShowDialog();
}

The solution to this problem is very simple by creating the Form instance within a using block. This will dispose the Form when it is closed.

private void buttonShowModalDialog(object sender, System.EventArgs e) {
    using (TestForm f = new TestForm()) {
        f.ShowDialog();
    }
}

An alternative solution uses a try/finnaly. Personally I prefer the previous, it is easier to read and write.

private void buttonShowModalDialog(object sender, System.EventArgs e) {
    TestForm f = null;
    try {
        f = new TestForm();
        f.ShowDialog();
    } finally {
        if (f != null) {
            f.Dispose();
        }
    }
}

The following solution isn't correct. You might think it is, but it isn't. The Dispose will not be executed when an Exception is thrown from within the ShowDialog().

private void buttonShowModalDialog(object sender, System.EventArgs e) {
    TestForm f = new TestForm();
    f.ShowDialog();
    f.Dispose();
}

« Previous Entries  Next Entries »