NathanTempelman
NathanTempelman

Reputation: 1387

Handle multiple events with the same event handler

I've got a notification, and I want to dismiss it with a click anywhere on the screen, or any keypress. Currently, I've got two methods that look like this

private void Dismiss(object sender, MouseEventArgs e)
{
    if(dismissable && dismissSeconds<=0)
    {
        FadeOut();
    }
}

private void Dismiss(object sender, KeyEventArgs e)
{
    if (dismissable && dismissSeconds <= 0)
    {
        FadeOut();
    }
}

I know that if the two objects send the same args type you can just select the same event handler in the properties window but since one returns KeyEventArgs and the other returns MouseEventArgs, that doesn't work.

If I'm not using the args anyway though, can I get rid of this duplicate code? Or am I going to confuse the designer if I start messing about?

Upvotes: 1

Views: 2423

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292695

Just extract the code to a new method that you call from the two event handlers:

private void Dismiss(object sender, MouseEventArgs e)
{
    Dismiss();
}

private void Dismiss(object sender, KeyEventArgs e)
{
    Dismiss();
}

private void Dismiss()
{
    if (dismissable && dismissSeconds <= 0)
    {
        FadeOut();
    }
}

Note that you could declare a single event handler, by specifying EventArgs as the parameter type:

private void Dismiss(object sender, EventArgs e)
{
    if (dismissable && dismissSeconds <= 0)
    {
        FadeOut();
    }
}

This way, the handler would be compatible with both events. However I wouldn't recommend doing that, because I think it's cleaner to keep things clearly separated. If someday you need to do something slightly different for the mouse event and the keyboard event, you will have more refactoring to do if you used a single handler.

Upvotes: 4

Related Questions