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.
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.