Dispose Modal WinForm Dialogs

By Fons Sonnemans, 12-12-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();
}

Leave a Comment

Leave a Comment
Name
Comment
6 + 3 =

0 Comments

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.