Event Listeners

In C#, we use event listeners to register the behavior we want to happen in response to specific events. You’ve probably already used these, i.e. declaring a listener:

private void OnEvent(object sender, EventArgs e) {
    // TODO: Respond to the event
}

Most event listeners follow the same pattern. They do not have a return value (their return type is void), and take two parameters. The first is always an object, and it is the source of the event (hence “sender”). The second is an EventArgs object, or a class descended from EventArgs, which provides details about the event.

For example, the various events dealing with mouse input (MouseMove, MouseDown, MouseUp) supply a <code>MouseEventArgs</code> object. This object includes properties defining the mouse location, number of clicks, mouse wheel rotations, and which button was involved in the event.

You’ve probably attached event listeners using the “Properties” panel in Visual Studio, but you can also add them in code:

Button button = new Button();
button.Click += OnClick;

Note you don’t include parenthesis after the name of the event listener. You aren’t invoking the event listener, you’re attaching it (so it can be invoked in the future when the event happens). Also, note that we use the += operator to signify attaching an event listener.

This syntax is a deliberate choice to help reinforce the idea that we can attach multiple event listeners in C#, i.e.:

Button button = new Button();
button.Click += onClick1;
button.Click += onClick2;

In this case, both onClick1 and onClick2 will be invoked when the button is clicked. This is also one reason to attach event listeners programmatically rather than through the “Properties” window (it can only attach one).

We can also remove an event listener if we no longer want it to be invoked when the event happens. We do this with the -= operator:

button.Click -= onClick1;

Again, note we use the listener’s name without parenthesis.