Click here to Skip to main content
13,291,254 members (57,041 online)
Click here to Skip to main content
Add your own
alternative version


614 bookmarked
Posted 15 Aug 2003

Events and Delegates Simplified

, 29 Nov 2012
Rate this:
Please Sign up or sign in to vote.
This article shows you how to design events for your classes.



When I was trying to learn events and delegates, I read a lot of articles to completely understand what they are and how to use them, and now I want to present them all here, everything I learned, most of the things you need to learn.

What are delegates?

Delegate and Event concepts are completely tied together. Delegates are just function pointers, That is, they hold references to functions.

A Delegate is a class. When you create an instance of it, you pass in the function name (as a parameter for the delegate's constructor) to which this delegate will refer.

Every delegate has a signature. For example:

Delegate int SomeDelegate(string s, bool b);

is a delegate declaration. When I say this delegate has a signature, I mean that it returns an int type and takes two parameters of type string and bool.

I said, when you instantiate delegates, you pass in the function name to which this delegate will refer as its constructor parameter. The important thing to notice is that only functions that have the same signature as the delegate, can be passed as a parameter.

Consider the following function:

private int SomeFunction(string str, bool bln){...}

You can pass this function to SomeDelegate's constructor, because of their similar signatures.

SomeDelegate sd = new SomeDelegate(SomeFunction);

Now, sd refers to SomeFunction, in other words, SomeFunction is registered to sd. If you call sd, SomeFunction will be invoked. Keep in mind what I mean by registered functions. Later, we will refer to registered functions.

sd("somestring", true);

Now that you know how to use delegates, let's understand events...

Understanding Events

  • A Button is a class, when you click on it, the click event fires.
  • A Timer is a class, every millisecond a tick event fires.

Want to understand what's happening? Let's learn through an example:

This is the scenario: we have a class named Counter. This class has a method named CountTo(int countTo, int reachableNum) which starts counting from 0 to countTo, and raises an event named NumberReached whenever it reaches the reachableNum.

Our class has an event: NumberReached. Events are variables of type delegates. I mean, if you want to declare an event, you just declare a variable of type some delegate and put event keyword before your declaration, like this:

public event NumberReachedEventHandler NumberReached;

In the above declaration, NumberReachedEventHandler is just a delegate. Maybe it was better to say: NumberReachedDelegate, but notice that Microsoft doesn't say MouseDelegate or PaintDelegate, instead it offers: MouseEventHandler and PaintEventHandler. It's a convention to say NumberReachedEventHandler instead of NumberReachedDelegate. OK? Good!

You see, before we declare our event, we need to define our delegate (our event handler). It could be something like this:

public delegate void NumberReachedEventHandler(object sender, 
    NumberReachedEventArgs e);

As you see, our delegate's name is: NumberReachedEventHandler, and its signature contains a void return value and two parameters of type object and NumberReachedEventArgs. If you somewhere want to instantiate this delegate, the function passed in as constructor parameter should have the same signature as this delegate.

Have you ever used PaintEventArgs or MouseEventArgs in your code to determine the position of the mouse, where it was moving, or the Graphics property of the object which raised the Paint event? Actually, we provide our data for the user in a class which is derived from EventArgs class. For example, in our example, we want to provide the number which was reached. And here is the class definition:

public class NumberReachedEventArgs : EventArgs
    private int _reached;
    public NumberReachedEventArgs(int num)
        this._reached = num;
    public int ReachedNumber
            return _reached;

If it wouldn't be necessary to provide the user with any information, we just use the EventArgs class.

Now, every thing is prepared to take a look inside our Counter class:

namespace Events
    public delegate void NumberReachedEventHandler(object sender, 
        NumberReachedEventArgs e);

    /// <summary>
    /// Summary description for Counter.
    /// </summary>
    public class Counter
        public event NumberReachedEventHandler NumberReached;
        public Counter()
            // TODO: Add constructor logic here
        public void CountTo(int countTo, int reachableNum)
            if(countTo < reachableNum)
                throw new ArgumentException(
                    "reachableNum should be less than countTo");
            for(int ctr=0;ctr<=countTo;ctr++)
                if(ctr == reachableNum)
                    NumberReachedEventArgs e = new NumberReachedEventArgs(
                    return;//don't count any more

        protected virtual void OnNumberReached(NumberReachedEventArgs e)
            if(NumberReached != null)
                NumberReached(this, e);//Raise the event

In the above code, we raise an event if we reach the desired number. There are a lot of things to consider here:

  • Raising an event is accomplished through calling our event (an instance of some delegate named NumberReachedEventHandler):
    NumberReached(this, e);

    This way, all registered functions will be invoked.

  • We prepare data for registered functions through this:
    NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
  • One question: why do we indirectly call NumberReached(this, e) through OnNumberReached(NumberReachedEventArgs e) method? Why didn't we use the following code?
    if(ctr == reachableNum)
        NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
        if(NumberReached != null)
            NumberReached(this, e);//Raise the event
        return;//don't count any more

    Good question! If you want to know why we called indirectly, take another look at OnNumberReached's signature:

    protected virtual void OnNumberReached(NumberReachedEventArgs e)
    • You see, this method is protected, it means it's available for classes which are derived from this class (inheriting classes).
    • This method is also virtual, this means that it could be overridden in a derived class.

    And this is very useful. Suppose you are designing a class which inherits from Counter class. By overriding OnNumberReached method, you can do some additional work in your class before the event gets raised. An example:

    protected override void OnNumberReached(NumberReachedEventArgs e)
        //Do additional work

    Note that if you don't call base.OnNumberReached(e), the event will never be raised! This might be useful when you are inheriting from some class and want to eliminate some of its events! An interesting trick, huh?

    As a real world example, you can just create a new ASP.NET Web Application and take a look inside the code behind generated. As you see, your page inherits from System.Web.UI.Page class. This class has a virtual and protected method name OnInit. You see that InitializeComponent() method is called inside the overridden method as an extra work, and then OnInit(e) is called in the base class:

    #region Web Form Designer generated code
    protected override void OnInit(EventArgs e)
        //CODEGEN: This call is required by the ASP.NET Web Form Designer.
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
          this.Load += new System.EventHandler(this.Page_Load);
  • Notice that NumberReachedEventHandler delegate is defined outside our class, inside the namespace, visible to all classes.

OK. Now, it's time to practically use our Counter class:

In our sample application, we have two textboxes named txtCountTo and txtReachable as follows:

sample application

And here is the event handler for btnRun click event:

private void cmdRun_Click(object sender, System.EventArgs e)
    if(txtCountTo.Text == "" || txtReachable.Text=="")
    oCounter = new Counter();
    oCounter.NumberReached += new NumberReachedEventHandler(

private void oCounter_NumberReached(object sender, NumberReachedEventArgs e)
    MessageBox.Show("Reached: " + e.ReachedNumber.ToString());

This is the syntax for initiating an event handler for some event:

oCounter.NumberReached += new NumberReachedEventHandler(

Now, you understand what you are doing here! You are just instantiating an object of type NumberReachedEventHandler delegate (as you do for any other object). Care about the oCounter_NumberReached method signature similarity as I mentioned before.

And notice that we used += instead of simply =.

It's because delegates are special objects that can hold references to more than one object (here, reference to more than one function). For example, if you had another function named oCounter_NumberReached2 with the same signature as oCounter_NumberReached, both of the functions could be referenced this way:

oCounter.NumberReached += new NumberReachedEventHandler(
oCounter.NumberReached += new NumberReachedEventHandler(

Now, after raising an event, both functions will be invoked one after another.

If somewhere in your code, based on conditions, you decided oCounter_NumberReached2 not be invoked anymore on NumberReached event occurrences, you could simply do this:

oCounter.NumberReached -= new NumberReachedEventHandler(

event Keyword

A lot of folks keep asking this question: "what happens if we don't use event keyword?"

In essence, declaring the event keyword prevents any of the delegate’s users from setting it to null. Why is this important? Imagine that as a client I would add to the delegates invocation list a callback to one of my class’ functions. So would other clients. All is well and good. Now imagine that someone, instead of using the “+=”, is simply setting the delegate to a new callback by using “=”. This basically just throws the old delegate and its invocation list down the drain and creates a whole new delegate with a single item in its invocation list. All the other clients will not receive their callbacks when the time comes. It is this kind of situation that having the event keyword is aiming to solve. If I keep the event keyword in the Counter class and try to compile the following code in my application, it will cause a compilation error. By removing the event keyword, however, this error will not happen.

In conclusion: an event declaration adds a layer of protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list, and only allows adding or removing targets from the invocation list [reference].


Don't forget to define these lines in your application's main constructor, instead of cmdRun_Click event handler. I defined them in my button click event handler just for the sake of simplicity! ;-)

public Form1()
    // Required for Windows Form Designer support

    // TODO: Add any constructor code after InitializeComponent call
    oCounter = new Counter();
    oCounter.NumberReached += new NumberReachedEventHandler(
    oCounter.NumberReached += new NumberReachedEventHandler(

The source code provided by this article is as above.

If your vote is less than 5, let me know the reason ;-). I hope you are satisfied after reading this article!


  • Thursday, August 21, 2003
    • The article has a better decorated coding.
    • Some image of demo application added.
  • Wednesday, August 11, 2004
    • Added an example of inheritance.
  • Saturday, March 12, 2005
    • More about the usage of event keyword.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Meysam Mahfouzi
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralRe: My vote of 4 Pin
Meysam Mahfouzi1-Dec-12 18:10
memberMeysam Mahfouzi1-Dec-12 18:10 
GeneralMy vote of 5 Pin
binog29-Nov-12 16:54
memberbinog29-Nov-12 16:54 
GeneralMy vote of 5 Pin
IFFI29-Nov-12 5:13
memberIFFI29-Nov-12 5:13 
GeneralMy vote of 5 Pin
Abang Jam1-Oct-12 16:36
memberAbang Jam1-Oct-12 16:36 
QuestionGood article Pin
amit_1410-Sep-12 1:50
memberamit_1410-Sep-12 1:50 
GeneralMy vote of 3 Pin
zahidbashir19-Jul-12 12:28
memberzahidbashir19-Jul-12 12:28 
GeneralRe: My vote of 3 Pin
Meysam Mahfouzi25-Jul-12 22:38
memberMeysam Mahfouzi25-Jul-12 22:38 
GeneralRe: My vote of 3 Pin
rchenna29-Nov-12 12:03
memberrchenna29-Nov-12 12:03 
QuestionGreat article Pin
Puneet Khurana16-Jul-12 21:58
memberPuneet Khurana16-Jul-12 21:58 
GeneralMy vote of 5 Pin
Puneet Khurana16-Jul-12 21:56
memberPuneet Khurana16-Jul-12 21:56 
GeneralMy vote of 5 Pin
Dr. noob19-May-12 3:56
memberDr. noob19-May-12 3:56 
QuestionGreat! Pin
Shandesh Poudel10-May-12 9:44
groupShandesh Poudel10-May-12 9:44 
GeneralMy vote of 5 Pin
Achintya Jha6-May-12 18:07
memberAchintya Jha6-May-12 18:07 
GeneralMy vote of 5 Pin
Arkham0010-Feb-12 7:20
memberArkham0010-Feb-12 7:20 
Simple, clear, complete.
QuestionMy 5 Points Pin
Atif Aslam9-Feb-12 1:50
memberAtif Aslam9-Feb-12 1:50 
GeneralMy vote of 5 Pin
Vinod Satapara29-Dec-11 23:48
memberVinod Satapara29-Dec-11 23:48 
GeneralMy vote of 5 Pin
loshuyan@gmail.com15-Dec-11 22:47
memberloshuyan@gmail.com15-Dec-11 22:47 
GeneralMy vote of 5 Pin
skrjabin373-Jul-11 5:10
memberskrjabin373-Jul-11 5:10 
QuestionDelegates in .Net 4 Pin
Anubalaji3-Jun-11 6:14
memberAnubalaji3-Jun-11 6:14 
AnswerRe: Delegates in .Net 4 Pin
Meysam Mahfouzi3-Jun-11 8:15
memberMeysam Mahfouzi3-Jun-11 8:15 
QuestionRe: Delegates in .Net 4 Pin
Anubalaji6-Jun-11 3:26
memberAnubalaji6-Jun-11 3:26 
GeneralSimple and Crisp Pin
WCFguru20-Apr-11 22:03
memberWCFguru20-Apr-11 22:03 
GeneralRe: Simple and Crisp Pin
Meysam Mahfouzi21-Apr-11 0:02
memberMeysam Mahfouzi21-Apr-11 0:02 
GeneralGreat Job Dude ! Keep it Up Pin
pakauman17-Apr-11 6:12
memberpakauman17-Apr-11 6:12 
GeneralRe: Great Job Dude ! Keep it Up Pin
Meysam Mahfouzi17-Apr-11 7:49
memberMeysam Mahfouzi17-Apr-11 7:49 
Generalvery well explained Pin
ron nec16-Apr-11 22:41
memberron nec16-Apr-11 22:41 
GeneralMy vote of 5 Pin
ngocson2vn15-Feb-11 23:45
memberngocson2vn15-Feb-11 23:45 
GeneralMy vote of 5 Pin
Frank884814-Feb-11 8:45
memberFrank884814-Feb-11 8:45 
GeneralNice Article Pin
arpitgold5-Feb-11 6:01
memberarpitgold5-Feb-11 6:01 
GeneralMy vote of 5 Pin
Hitechdinesh20-Jan-11 0:28
memberHitechdinesh20-Jan-11 0:28 
GeneralMy vote of 5 Pin
raclog19-Nov-10 5:48
memberraclog19-Nov-10 5:48 
GeneralMy vote of 5 Pin
bjagadish0626-Oct-10 23:41
memberbjagadish0626-Oct-10 23:41 
GeneralMy vote of 5 Pin
Michael Hildebrand14-Oct-10 8:54
memberMichael Hildebrand14-Oct-10 8:54 
GeneralMy vote of 5 Pin
Member 286099114-Sep-10 2:39
memberMember 286099114-Sep-10 2:39 
GeneralMy vote of 5 Pin
pradeep41319326-Aug-10 3:15
memberpradeep41319326-Aug-10 3:15 
Generala querry about Pin
rohandm2913-Aug-10 6:37
memberrohandm2913-Aug-10 6:37 
GeneralIt got compiled in same class. Pin
anunet28-Jul-10 11:18
memberanunet28-Jul-10 11:18 
GeneralRe: It got compiled in same class. Pin
Maysam Mahfouzi28-Jul-10 21:10
memberMaysam Mahfouzi28-Jul-10 21:10 
GeneralRe: It got compiled in same class. Pin
DaveyM6913-Nov-12 2:31
mentorDaveyM6913-Nov-12 2:31 
GeneralMy vote of 5 Pin
RohitPatil1126-Jul-10 8:56
memberRohitPatil1126-Jul-10 8:56 
GeneralMy vote of 5 Pin
mOOdyGuy30-Jun-10 2:12
membermOOdyGuy30-Jun-10 2:12 
GeneralExtremely useful! Pin
aeternam3-May-10 1:40
memberaeternam3-May-10 1:40 
GeneralNice work done Pin
Wahab Hussain24-Mar-10 1:12
memberWahab Hussain24-Mar-10 1:12 
GeneralOutstanding! Pin
thund3rstruck10-Mar-10 14:11
memberthund3rstruck10-Mar-10 14:11 
GeneralNice Pin
Pravin S. Kadam11-Feb-10 0:26
memberPravin S. Kadam11-Feb-10 0:26 
GeneralGOOD Pin
pune25-Nov-09 7:51
memberpune25-Nov-09 7:51 
GeneralNice work Pin
gar0831-Oct-09 18:19
membergar0831-Oct-09 18:19 
GeneralSystem.EventHandler and System.EventHandler<t></t> Pin
Tomas0028-Sep-09 0:02
memberTomas0028-Sep-09 0:02 
Generalcool Pin
gaobanana20-Sep-09 23:09
membergaobanana20-Sep-09 23:09 
GeneralRe: cool Pin
Maysam Mahfouzi20-Sep-09 23:18
memberMaysam Mahfouzi20-Sep-09 23:18 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 29 Nov 2012
Article Copyright 2003 by Meysam Mahfouzi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid