Which is a better way to call Form.ShowDialog()?

Stack Overflow picture Stack Overflow · Dec 24, 2011 · Viewed 21.4k times · Source

Which is a better way to show a modal dialog?

form1 frm=new form1();
frm.showDialog()

or

(new form1()).showDialog();

Answer

Cody Gray picture Cody Gray · Dec 24, 2011

Neither one is "better" than the other; they are perfectly equivalent!

However, in this particular case, both are wrong. The ShowDialog method requires you to call the Dispose method on the form. Unlike the Show and Close combination, this is not done automatically. From MSDN:

When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel. Unlike non-modal forms, the Close method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of the DialogResult property. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Because a form displayed as a dialog box is hidden instead of closed, you must call the Dispose method of the form when the form is no longer needed by your application.

Thus, you should choose between one of these (equivalent) forms:

using (Form1 frm = new Form1())
{
    frm.ShowDialog();
}

or

Form1 frm = new Form1();
frm.ShowDialog();
frm.Dispose();

The reason that ShowDialog doesn't automatically dispose the form is simple enough, if not immediately obvious. It turns out that applications often wish to read values from an instance of a modal dialog form after the form has been closed, such as settings specified in the form's controls. If the form were automatically disposed, you would be unable to read those values by accessing properties of the form object. Thus, the programmer is responsible for disposing forms shown as modal dialogs when (s)he is finished with them.