Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Why does form.Close() not close the form?

Tags:

c#

winforms

I have a button click event handler with the following pseudo code:

private void btnSave_Click(object sender, EventArgs e)
{
  if(txt.Text.length == 0)
     this.Close();
  else
     // Do something else

  // Some other code...
}

This is just some simple code, but the point is, when the text length equals zero, I want to close the form. But instead of closing the form the code executes the part // Some other code. After the click event handler is completely executed, then the form is closed.

I know, when I place return right after this.Close() the form will close, but I'd like to know WHY the form isn't direclty closed when you call this.Close(). Why is the rest of the event handler executed?

like image 442
Martijn Avatar asked Oct 12 '10 08:10

Martijn


2 Answers

The rest of the event handler is executed because you did not leave the method. It is as simple as that.

Calling this.Close() does not immediately "delete" the form (and the current event handler). The form will be collected later on by the garbage collector if there are no more references to the form.

this.Close() is nothing than a regular method call, and unless the method throws an exception you will stay in the context of your current method.

like image 132
Dirk Vollmar Avatar answered Oct 12 '22 17:10

Dirk Vollmar


Close only hides the form; the form is still alive and won't receive another Load event if you show it again.

To actually delete it from memory, use Dispose().

like image 44
vulkanino Avatar answered Oct 12 '22 18:10

vulkanino