Search code examples
c#refactoringcode-duplication

Elegant way to reduce code duplication between prompting the user to save when closing the program?


When exiting the program if the programmer handles the FormClosing event if there is unsaved data the programmer can prompt a save dialog asking them if they want to save, not save, or cancel the operation.

In the FormClosing event if they hit Cancel, to cancel the operation you set e.Cancel = true;. This is fine. However, in the menu if the user hits the Exit button then the same thing should occur except instead of doing e.Cancel = true; it should just do return; because it's handle menu item Click event instead of a FormClosing event.

Right now I pretty much have the code duplicated and was wondering if there was a way to handle this to avoid the duplication in an elegant and understandable fashion.

private void FrmEditorFormClosing(object sender, FormClosingEventArgs e)
{
    if (NeedsToSave)
    {
        DialogResult saveChangesDialog = 
MessageBox.Show("There are unsaved changes. Save now?", 
"Xml Editor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

        if (saveChangesDialog == DialogResult.Yes)
        {
            Save();
        }
        else if (saveChangesDialog == DialogResult.Cancel)
        {
            e.Cancel = true; // Only difference
        }
    }
}

private void ExitToolStripMenuItemClick(object sender, EventArgs e)
{
    if (NeedsToSave)
    {
        DialogResult saveChangesDialog = 
MessageBox.Show("There are unsaved changes. Save now?", 
"Xml Editor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

        if (saveChangesDialog == DialogResult.Yes)
        {
            Save();
        }
        else if (saveChangesDialog == DialogResult.Cancel)
        {
            return; // Only difference
        }
    }

    Close();
}

Solution

  • You shouldn't need to do this. Calling Close in your menu click handler should cause the FormClosing event to fire and you can cancel it there.