I have a MDI form where some of the children forms need a message box showing before being closed and others could be closed without asking. Because of a problem when calling application.Exit() from a close event of a child form I handle to close event of the parent and check where it was fired. If it was fired in a form that need a message box I call it otherwise just close the application. All this is implemented in this code:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
SEdit se = this.ActiveMdiChild as SEdit;
SoEdit soleEdit = this.ActiveControl as SoEdit;
UppEdit ue = this.ActiveControl as UpEdit;
MEdit mat = this.ActiveControl as MEdit;
LEdit lse = this.ActiveControl as LEdit;
CEdit cle = this.ActiveControl as CEdit;
if (se != null || soleEdit != null || ue != null || mat != null || lse != null || cle != null)
{
if (MessageBox.Show("Do you want to save before exit?", "Closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.Yes)
{
MessageBox.Show("To Do saved.", "Status",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}
I’m still learning but I know that such a long if-statement is a sign for bad code but i don’t know how to improve it. What is the proper way to handle this situation?
Extract condition to separate method:
Then call this method (also use guard conditions to avoid nested if statements):