Proper way to dispose a new Form

Do I need to Dispose a Form after closing the Form?

When you show the form using Show() you don’t need to dispose it, because it will dispose after close. But when you show form using ShowDialog(), you need to dispose the form, because it won’t dispose after closing.

When you close a Form, a WM_CLOSE message will be sent to the window. If you take a look at source code of WmClose method which handles WM_CLOSE message, you will see:

  • For modal forms (which you showed using ShowDialog), the Dispose method will not be called and the form exists after closing and you can use its properties to get some data or you can show it again.

  • For non-modal forms (which you showed using Show), after the form got closed, the Dispose method will be called.

So here is the conclusion:

  • When you show a form using Show method you don’t need to (and you can’t) call Dispose. The form will be disposed itself after got closed.

  • When you show a form using ShowDialog you need to call Dispose manually. A good practice is use modal forms in a using block.

Example

To show a modal dialog, as a best practice use a using block:

//form will be disposed after the using block
using (var f = new MyForm())
{
    if (f.ShowDialog() == DialogResult.OK)
    {
        //Your logic to handle OK here
    }
}

For a non-modal dialog, show and forget about it:

var f = new MyForm();
f.Show();

Leave a Comment