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?
G
EDIT: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?
If you hit X to close a modal form, the form is actually hidden. You have to manually call dispose to release the resource.
See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult.aspx
One option is to run FxCop over your assemblies. One of its rules will verify that Dispose is being called on all objects that implement IDisposable, and warn you if you have violations.
EDIT: To answer your later question, Dispose is not automatically called. You need to handle that yourself. Here is one article on the subject.
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).
You could verify with the is operator, that a object is implementing IDisposable: