tags:

views:

59

answers:

2

When I create a Form, the auto-generated code doesn't include an overrided Dispose method. Does that mean Dispose is not being called for all the controls in the form?

+2  A: 

It should. You might have to look in the YourForm.designer.cs file. It will look like this:

protected override void Dispose(bool disposing)
{
   if(disposing && (components != null))
   {
      components.Dispose();
   }
   base.Dispose(disposing)
}

The base.Dispose(); call will take care of cleaning up the controls added to the Form.

SwDevMan81
That is not quite true; the `components` field is `null` unless you have non-UI components (such as a `Timer`, `HelpProvider` or `BackgroundWorker`) on the form. `components` handles disposing those components. It does *not* call dispose on other controls such as buttons, text boxes and so on.
Fredrik Mörk
Exactly, the form's controls are actually disposed via the call to `base.Dispose()`, namely inside `Control.Dispose()`. There is a lot more cleaning up going actually as you will see when looking into `Form.Dispose()` with Reflector.
0xA3
Updates, thanks for the comments
SwDevMan81
+5  A: 

When you call Dispose on the form, it will call Dispose for each control in its Controls collection. Those controls will in turn do the same, so in the end all controls' Dispose method should have been invoked. Note that this is not based on whether the controls are present in the designer or not; it is based on what control instances that are found in the Controls collection of the form at the time the call to Dispose is done.

The only case when I could see that this would not happen is if you create some container control yourself and override Dispose without propagating the call either to the base class or iterate over the contained controls and call Dispose on them.

Fredrik Mörk
Yup. The components are done differently, that's what the auto-generated Dispose() method takes care of. Removing a control from the Controls collection and not disposing it is a good way to leak.
Hans Passant