.netcontrolsdispose

When should I manually dispose of controls? How do I know if a control implements IDisposable?


In a previous question about ridding the system tray of an old NotifyIcon I was told that I should Dispose anything that implements IDisposable. Sounds like good practise to me however as a newbie it raises more questions :-)

How do I know if a control implements IDisposable?

Should I build a class that attempts to dispose everything on all my forms in the formclosed event?

Something like this?(psuedocode):

foreach(control cont in form)  
{  
try{cont.Dispose()}  
catch{}  
}

  

If not, then how do I know what controls I would need to manually dispose, or should I simply watch for unusual behaviour during testing?

So when I click the big red "X" on my child form, that doesn't cause it to Dispose? is that right? What is the reason for this?


Solution

  • Any control that is owned by the form is disposed of when the form is disposed of. In other words, when calling Dispose(), a control will call Dispose() on all of its children. Note that hiding a form will not call Dispose(), but in most cases it's fine to just create a dialog and dispose of it as needed.

    This is always the case for designer-generated forms and controls. If you create a non-visual component like NotifyIcon in code (without setting the owner), you have to manually dispose of it. But it's usually easier to set the owner properly.

    Any class implementing IDisposable should call Dispose() on its childs, no matter if in a collection or in a property, unless there's a good reason not to (i.e. in some cases the caller might stay the owner of an object - but that's exactly where the concept of setting the ownership is for).