views:

136

answers:

2

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.

+6  A: 

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.

Jon Skeet
Hi Jon, thanks.So is that the right way of doing it? (using "using")But shouldn't .NET automatic GC detect that the form is declared within the button_click function and hence wouldn't be available outside the scope, and should free it when it finishes executing the function?
No, the GC doesn't do that at all. It would have to know that nothing in any of the rest of the code (including f.ShowDialog()) would stash a reference anywhere. And yes, a "using" statement is the right way of doing this.
Jon Skeet
+4  A: 

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.

aks
While you do have to do it yourself, I'd rather use a "using" statement than just calling Close explicitly.
Jon Skeet