Martijn Martijn - 3 months ago 11
C# Question

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

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?

Answer

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.

Comments