Question about cleaning up resources

Hi,

I have read that this.Close(); does not only closes the form but cleans
up the variable in memory also. So I have put the line when the user closes the
main form. But what about other forms. F.e I have a second form called Settings.
That can be called by mainmenu-item Settings it will then execute the following code:

        private void mmSettings_Click(object sender, EventArgs e)
        {
                        frmSettings.ShowDialog();
          }    

and it has a close-button:

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

But doesn't this close the settingsform and not clean up the form in memory?
How can I close the form and clean up the form in memory?
And is the keyword 'Dispose' for cleaning up objects?

Peter
LVL 1
peterkiersAsked:
Who is Participating?
 
AndyAinscowConnect With a Mentor Freelance programmer / ConsultantCommented:
     private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;  //Signal what the return of the form will be WHEN closed

this.Close();  //Now close the form
        }
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
Dispose should be called automatically for a form - you should not need to call it explicitly.

The memory is only 'cleaned' when the variable goes out of scope (and the garbage collector runs).

eg. some air code

{
MyForm frm =new MyForm();  //assign memory for the frm variable
frm.ShowDialog();  //Display the dialog as modal
int x = frm.SomeIntVariable;  //frm still exists (note NOT displayed) and is valid
}
int y = frm.SomeOtherInt;  //frm is now out off scope and invalid - error if you attempt to use it
0
 
peterkiersAuthor Commented:
Thanks.

Peter
0
 
Asim NazirCommented:
If you are sure that you are not going to referenc this form after closing it then best way is to dispose it instead of closing it. else If you want to access some properties of the form once form is closed then you can close it. Once closed, you can access any properties defined in the form and then dispose it.

This is the best implementation.

Asim
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.