Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Form.Dispose() call controls inside's Dispose()?

Tags:

c#

.net

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?

like image 669
Juan Avatar asked Sep 08 '10 18:09

Juan


People also ask

Does form close call Dispose?

After you close the form by Close or by clicking on X, it will be disposed automatically. Did you open the form using ShowDialog ? If you want to reuse it later, then do not forget to explicitly Dispose in when you no more need it.

What does dispose method do with?

The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

When the Dispose method is called?

It only occurs when there are objects in the Finalization Queue. It only occurs when a garbage collection occurs for Gen2 (which is approx 1 in every 100 collections for a well-written . NET app).

Who will call Dispose method C#?

NET Garbage Collector (GC). Before the GC deallocates the memory, the framework calls the object's Finalize() method, but developers are responsible for calling the Dispose() method. The two methods are not equivalent.


2 Answers

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.

like image 82
Fredrik Mörk Avatar answered Sep 28 '22 07:09

Fredrik Mörk


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.

like image 33
SwDevMan81 Avatar answered Sep 28 '22 08:09

SwDevMan81