How event handlers are implemented in C#.

Event handlers are methods that are executed in response to specific events that the component receives.

 

The following are notes of my reading of "How events are implemented" section of CLR via C# by Jeffrey Richter.

Event handler in C# are implemented via Delegates.

public event EventHandler<NewMailEventArgs> NewMail;

For example, the above single line of event handler are transformed into three delegate constructs. first, a field of the appropriate delegate type is referenced to the head of a list of delegates that will be notified when this event occurs. This field is initialized to null. When a method registers interest in the event, this field is refers to an instance of the EventHandler<NewMailEventArgs> delegate. When a listener registers interest in an event, the listener registers interest in an event, the listener is simply adding an instance of the delegate type to the list. The delegate filed, NewMail is always private  even if the origianl definition of the event handler is public in order to avoid 3rd party to change the event handler. The second construct is a method which allows you to register a new event to the event handler, third, a method which allows your unregister the event will be implemented. These methods are marked as synchronized, making them thread safe, multiple listeners can register or unregister themselves with the event at the same time without corrupting the list. The add and remove methods have the same permission level as the declared event handler.  The same rule applies to static or virtual as well.