What is an event?

Events allow classes to notify other classes when something occurs. Graphical User Interfaces (GUI) applications often use events to indicate when something occurs. One example is when a button is pressed and another class is listening to handle that event. There are multiple components to an event. Each component is discussed with example syntax below. Following these syntaxes, there’s an example with all the components combined.

An event needs to be defined inside a class. Using the event keyword enables others to attach to this event. Specify the delegate type for the type of methods that can be attached to the event. In the example below, a predefined delegate called EventHandler is used. The EventHandler delegate returns void and has two parameters (object, EventArgs). The object is the sender (what sent the event) and the EventArgs object(contains basic information about the event).

Get hands-on with 1200+ tech skills courses.