Event Handler

Why Trust Techopedia

What Does Event Handler Mean?

An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application.

Advertisements

Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface. A single event handler can be used to process events raised by multiple controls. An event can be associated with multiple event handlers, which will be invoked synchronously when the even occurs. Event handlers can also be used to handle events that signal an object’s state changes to the object’s clients.

Techopedia Explains Event Handler

The C# event model is based on a “publish-subscribe” pattern in which a class (publisher) triggers an event, while another class (subscriber) receives that event. An event handler is the subscriber that contains the code to handle specific events.

For example, an event handler can be used to handle an event that occurs during the click of a command button in the UI.

In C#, an event is connected to its handler by an event delegate. To raise an event and respond to the event, the two necessary elements are the delegate that links the event to its handler method and the class that holds event data. By adding the delegate instance to the event object using the addition assignment operator (‘+=’), the event handler is called on occurrence of its associated event.

The signature of an event handler delegate includes two parameters that represent the object instance raising the event and the object holding event data. The signature of an event handler method should match with that of the delegate for that event and with the return type as void. The .NET framework provides a built-in event handler that can be used in cases where the delegates used differ only by type name and hence can reduce code that needs to be maintained.

Advertisements

Related Terms

Margaret Rouse
Technology expert
Margaret Rouse
Technology expert

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.