I just wanted to clarify an issue that comes up once in a while. It is rather
poorly documented and can make one spend some time figuring it out.
Many times a developer writing CF code would do something like this:
MyForm form = new MyForm();
form.ShowDialog();
... rest of the function
What do you expect to happen to the form when the variable goes out of scope?
It is supposed to become a victim of the garbage collector, right? Wrong. To see what
really happens let's consider even simpler case:
Control c = new Control();
c = null;
You would think simply creating the control will have it unattached to anything
(like a parent control) and thus subject to garbage collection. Apparently not so.
If we look inside the Control object constructor, we will see that upon creation the
Control is added to an internally maintained list of all controls in the application:
Control()
{
... create new control...
Control.m_rlctlMaster.Add(this);
... do more housekeeping
}
m_rlctlMaster is an ArrayList - an internal static member of Control class.
The repercussions of the above action are rather obvious - the control is always referenced
by the control list. It refrence count never becomes zero unless you destroy it explicitly.
When control is destroyed, it destroys all its child controls. This means that
you do not have to explicitly kill every label, textbox and panel - it is enough to
delete the form. If however the control was dynamically removed from the parent form:
myPanel.Parent = null;
or
myForm.Controls.Remove(myPanel);
it becomes orphaned and needs to be destroyed explicitly by calling Control.Dispose()
Same thing is true for forms. What the code in the beginning of this post is
missing is form.Dispose(). Without it the form and all its controls will stay in memory
consuming resources and eventually will bog down the whole application