Aximili
Aximili

Reputation: 29464

.NET WinForm GC question

Is this code clean?

private void button1_Click(object sender, EventArgs e)
{
  frmCustomDialog f = new frmCustomDialog();
  if(f.ShowDialog() == DialogResult.OK)
    TextBox1.Text = f.MyCustomProperty;
}

Do you need to close or dispose the form f or anything? Or is it automatically garbage-collected?

Thank you.

Upvotes: 1

Views: 271

Answers (2)

aks
aks

Reputation: 292

If you are showing form as dialog form (which you are since you're calling it with the form.ShowDialog()), then you have to manually dispose of the object, because Close method of the form is not automatically called when closing the form (the form is hidden instead).

You can read more here.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500495

Yes, you should dispose of the form:

private void button1_Click(object sender, EventArgs e)
{
    using (frmCustomDialog f = new frmCustomDialog())
    {
        if(f.ShowDialog() == DialogResult.OK)
        {
            TextBox1.Text = f.MyCustomProperty;
        }
    }
}

ShowDialog() doesn't dispose of the form as you can reuse it and show it again. If you don't need to do this, you should just dispose it yourself.

From the docs of ShowDialog():

Unlike modeless 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 not closed, you must call the Dispose method of the form when the form is no longer needed by your application.

Upvotes: 7

Related Questions