Let’s say I have a form SomeForm that inherits from Form.
public class SomeForm : Form
{
private void SomeForm_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("FormClosed event in SomeForm class");
}
}
public class Consumer
{
SomeForm someForm = new SomeForm();
someForm = null; //Ideally the messagebox would display here
SomeForm someForm = new SomeForm();
someForm.Close(); //Messagebox would display in this case as well
}
I want to show that MessageBox whenever the form is closed. Should I stick that in the FormClosed event? Is it safe to assume that the FormClosed event will fire every time something like the destructor is run? Is there a better place to put this code that must occur when the form is closed?
EDIT
Someone made a good point in the comments below. It seems the event does not fire when the instance of the class is set to null. However, will the destructor or some other method still be called when the instance is set to null. I want to guarantee that my code runs when the user is finished with the class.
I’m also aware that forcibly shutting down the system, ending the process, acts of God, etc will not cause my code to run no matter what. =)
Yes, it will be called unless something exceptionably happens, like killing it via system commands or pulling the plug. Other cases include
null(not calling theClosemethod)MulticastDelegates, and the delegates are executed in order of appearence in thatMulticastDelegate, if one of the previous delegates before yours causes an exception, your delegate will not be called.