Forms and Dispose


As I have mentioned before, there is a wealth of knowledge to be gained from reading
internal Microsoft mailing lists. I plan to share some of that when I get a chance
– under the category .NET
– Random Tips
. Here is one such.

If you have code like this:

private void Foo() {

     MyForm f = new MyForm();

     f.Show();
}

Does f get garbage collected when Foo() returns?

Mark
Boulter
 clarifies:

No, the Form will not be garbage collected until it is closed and disposed.

More on automatic form disposal:

  • Modal Forms (ShowDialog)
    do not get automatically Disposed on Close.
  • Modeless Forms (Show)
    get automatically Disposed on Close.

Comments (2)

  1. Matthew Adams says:

    And don’t forget that Dispose() has nothing to do with garbage collection, and everything to do with freeing up unmanaged resources (like your Window handles). There is nothing to stop you continuing to call methods on a Disposed object, except convention and/or specifically documented semantics.

  2. milbertus says:

    At first, I didn’t understand why modal forms wouldn’t get automatically disposed on Close, but then it dawned on me. I personally set up public properties for any data that the user enters into the form, so if the form was disposed as soon as it was closed, my code wouldn’t be able to get to those properties.