Events and Delegates in C#

Events:

An event is a delegate type class member that is used by the object or class to provide a notification to other objects that an event has occurred. The client object can act on an event by adding an event handler to the event. It has the following syntax:

modifier event type event-name;

Where the modifier may be new, a valid combination of the four access modifiers, and a valid combination of static, virtual, override, abstract and sealed. The type of an event declaration must be a delegate type and it must be as accessible as the event itself. The event-name is any valid C# variable name.

Example:

public event EventHandler Click;
public event RateChange Rate;

Where EventHandler and RateChange are delegates and Click and Rate are events.

Delegates:

Delegate means that ‘A person acting for another person. In C#, it means that a method acts for another method. Delegate is a class type object that is used to involve a method that has been encapsulated into it at the time of its creation. In C#, Delegates are used for two purposes:

  • Callback
  • Event Handling
  • There are four steps to create a delegate:
    1. Delegate declaration
    2. Delegate methods definition
    3. Delegate instantiation
    4. Delegate invocation