Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

How Events Work Under the Surface

Rate me:
Please Sign up or sign in to vote.
4.64/5 (44 votes)
1 Jan 20072 min read 80.3K   270   67   23
Shows what goes on behind the "magic" that the compiler does when you declare a simple event member in a class.

Introduction

This article aims to show you what goes on behind the "magic" that the compiler does when you declare a simple event member in a class. It is meant as a beginner article to answer a frequently-asked question, so please don't vote it down just because it is very basic.


Multicast Delegates: The Foundation of Events

A pre-requisite to understanding how events work under the surface is to understand how multicast delegates work. A multicast delegate is a combined delegate that is made up of multiple single delegates joined together into a single object. The delegate can be called the same way you would call a normal delegate that only represents a reference to one method, but it will invoke all the methods it represents each time it is called. Let's see this in action. Say we have 2 methods in a class, named MyMethod1 and MyMethod2:

C#
public void MyMethod1()
{
    Console.WriteLine("Method 1");
}

public void MyMethod2()
{
    Console.WriteLine("Method 2");
}

The methods have no parameters or return value so we create an "empty" delegate signature with no return value or arguments:

C#
public delegate void EmptyDelegate();

Now, we want to call both delegates at once, so we use Delegate.Combine() to create a combined delegate, with references to both methods:

C#
//Create a new multicast delegate that contains references to 
//both methods at once.
EmptyDelegate multicast=(EmptyDelegate)Delegate.Combine(
    new EmptyDelegate(MyMethod1),
    new EmptyDelegate(MyMethod2)
    );
//Call the new multicast delegate.
multicast();

When the multicast delegate is called, both methods will be executed in the order they were combined in, so the console output will be:

Method 1
Method 2

How Events Are Implemented

Now that we've seen how multi-cast delegates work, let's look at how events make use of them. An event is a wrapper over a multi-cast delegate field, that only allows outside objects to add and remove handlers. To better understand how this works, let's look at the more verbose way to declare an event.

First, define a field whose data type is a delegate type (in this case EventHandler):

C#
private EventHandler myEventHandlers;

This is a simple field that can hold a multi-cast delegate containing references to all the handlers that are listening to the event.

Next we define a special event declaration, that is much like a property in its syntax, but it is declared with the event keyword, instead of get and set accessors, to get and set a property value, it has add and remove accessors, to add and remove handlers from the event. Notice the use of Delegate.Combine() to combine delegates, and Delegate.Remove() to remove a single delegate from a multi-cast delegate.

C#
//Event declaration - similar in syntax to a property declaration
public event EventHandler MyEvent
{
    add
    {
        //Combine the multi-cast delegate that has the existing handlers
        //with the new handler delegate, to make a new multi-cast delegate 
        //that includes both the existing handlers and the new handler.
        myEventHandlers = (EventHandler)
            Delegate.Combine(myEventHandlers, value);
    }
    remove
    {
        //Create a new multi-cast delegate that contains all 
        //the existing handlers,
        //except for the one that's being removed.
        myEventHandlers = (EventHandler)
            Delegate.Remove(myEventHandlers, value);
    }
}

This will result in the same generated code as the normal type of declaration will:

C#
public event EventHandler MyEvent;

So there you go: underneath, an event is a multi-cast delegate in a private field (member variable), and then a special public accessor that only allows adding and removing handlers from the multi-cast delegate.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
My main goal as a developer is to improve the way software is designed, and how it interacts with the user. I like designing software best, but I also like coding and documentation. I especially like to work with user interfaces and graphics.

I have extensive knowledge of the .NET Framework, and like to delve into its internals. I specialize in working with VG.net and MyXaml. I also like to work with ASP.NET, AJAX, and DHTML.

Comments and Discussions

 
Questionevent or thread,which one is more efficient ? ? Pin
okcode7-Aug-11 13:12
okcode7-Aug-11 13:12 
QuestionHelp Please Pin
redcat2220-Jan-07 8:32
redcat2220-Jan-07 8:32 
AnswerRe: Help Please Pin
rdkerr31-Jan-07 19:08
rdkerr31-Jan-07 19:08 
General.NET 2.0 makes it a bit easier Pin
Daniel Ruehmer8-Jan-07 22:08
Daniel Ruehmer8-Jan-07 22:08 
GeneralExceptions Pin
Josh Smith8-Jan-07 11:56
Josh Smith8-Jan-07 11:56 
GeneralAnother using of events Pin
Ertan Tike8-Jan-07 8:00
Ertan Tike8-Jan-07 8:00 
GeneralRe: Another using of events Pin
tlongman8-Jan-07 19:49
tlongman8-Jan-07 19:49 
GeneralNice refresher... Pin
0xfded3-Jan-07 3:29
0xfded3-Jan-07 3:29 
QuestionLocking??? Pin
James Ivie3-Jan-07 2:47
James Ivie3-Jan-07 2:47 
AnswerRe: Locking??? Pin
J. Dunlap3-Jan-07 3:00
J. Dunlap3-Jan-07 3:00 
GeneralRe: Locking??? Pin
James Ivie3-Jan-07 11:00
James Ivie3-Jan-07 11:00 
GeneralDelegates Pin
Spiff Dog2-Jan-07 9:13
Spiff Dog2-Jan-07 9:13 
GeneralRe: Delegates Pin
J. Dunlap3-Jan-07 3:24
J. Dunlap3-Jan-07 3:24 
GeneralExtra info Pin
leppie1-Jan-07 21:56
leppie1-Jan-07 21:56 
GeneralRe: Extra info Pin
J. Dunlap3-Jan-07 3:20
J. Dunlap3-Jan-07 3:20 
GeneralRe: Extra info Pin
rdkerr22-Jan-07 12:24
rdkerr22-Jan-07 12:24 
GeneralRe: Extra info Pin
leppie22-Jan-07 18:22
leppie22-Jan-07 18:22 
GeneralVery good and solid article Pin
Martin#1-Jan-07 19:38
Martin#1-Jan-07 19:38 
GeneralRe: Very good and solid article Pin
J. Dunlap3-Jan-07 3:20
J. Dunlap3-Jan-07 3:20 
Generalthanks for the article... Pin
subai1-Jan-07 19:09
subai1-Jan-07 19:09 
thank you for your article .
i think events in asp are more confusing Smile | :)

I Wish the Life Had CTRL-Z

GeneralRe: thanks for the article... Pin
J. Dunlap3-Jan-07 3:20
J. Dunlap3-Jan-07 3:20 
GeneralGood idea - well done. Pin
Pete O'Hanlon1-Jan-07 10:05
subeditorPete O'Hanlon1-Jan-07 10:05 
GeneralRe: Good idea - well done. Pin
J. Dunlap1-Jan-07 12:12
J. Dunlap1-Jan-07 12:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.