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

Event Delegates in Simple English (Really, it's that simple)

Rate me:
Please Sign up or sign in to vote.
4.69/5 (27 votes)
24 Jun 20032 min read 95.3K   1.2K   51   7
A simple tutorial for beginners on the daunting Event Delegates (C#).

Sample Image - EventDelegates.gif

Introduction

This article is meant to be a step by step guide to give its reader an understanding of Event Delegates. It's a bit daunting for newbies to .NET. But I'll try my best to break it down to beginners here...

Event Delegates as simple as 1, 2, 3

In short, event delegates aren't hard to understand... maybe the thing that perhaps makes it hard to understand is that it's not very straightforward.

Basically, we have to understand 3 things - Yes! Only 3:

  1. Firstly, we have a class that publishes or advertises events (let's call it EventPublisher). It will have a delegate and event declaration like so:
    C#
    //We declare the event itself here
    public event EventDelegate myEvent;
    //Our delegation here (in simple english), is to 
    //publish our event. It sort of says "hey everyone, we have an
    //event here that you can subscribe to"...
    public delegate void EventDelegate(object from, EventArgs args);
  2. Our EventSubscriber (you can have many of this), that wants to respond to must implement a function to handle that event. It will add a reference (or connect, in simple English) to one of its methods to the EventPublisher's class event delegate.
    C#
    //Here (in simple English), we (this class) want to subscribe to this
    //event delegate (EventDelegate) of EventPublisher. So if the EventPublisher
    //raises any event, please send the event to our method this_OnProgress...
    theClass3.myEvent += new EventPublisher.EventDelegate(this_OnProgress);

    The subscriber will have a method to handle the event:

    C#
    private void this_OnProgress( object sender, EventArgs e)
    {
      //Your event handler code goes here
      //We could play the infamous "mail arrived" sound here
      Console.WriteLine("Event handled in this_OnProgress of EventSubscriber");
      //Our sender object gives us some info...
      //In your real app, you would read the EventArgs, for example
      Console.WriteLine("Sender:" + sender.ToString());
    }
  3. When the EventPublisher class wants to raise an event, it simply calls the delegate. Now, what happens at this point is that, all the subscribers will then be asked to handle the event.
    C#
    //This is where we raise the event from the EventPublisher class
      public void issueEvent(EventArgs args)
      {
        if (myEvent!= null)
        {
            myEvent(this, args);
        }
      }

    There's a hidden last step: after you're done, simply unsubscribe the event:

    C#
    ~EventSubscriber()
    {
      theClass3.myEvent -= new EventPublisher.EventDelegate(this_OnProgress);
    }

Using the code (EventPublisher.cs)

The solution

  1. To start, create an empty solution.
  2. Add a new class library project called TryThis.
  3. Change the default .cs name to EventPublisher.cs.
  4. Copy the code below (be sure to read the comments as we go on).

This guy down here is the guy who 'advertises' the event.

C#
using System;
/// <summary>
/// Summary description for EventPublisher.
/// </summary>
///

public class EventPublisher
{
  //We declare the event itself here
  public event EventDelegate myEvent;
  //Our delegation here (in simple english), is to
  //publish our event. It sort of says "hey everyone, we have an
  //event here that you can subscribe to"...
  public delegate void EventDelegate(object from, EventArgs args);
  //This is where we raise the event from the EventPublisher class
  public void issueEvent(EventArgs args)
  {
    myEvent(this, args);
  }

  //We don't need any logic for the constructor, to keep it simple
  public EventPublisher()
  {
  }
  //This is the event trigger
  //The reason I seperated this is because I wanted to show you
  //that we can pass EventArgs to issueEvent
  //Usually we will inherit from EventArgs and create our own
  //data structure to send information pertaining to the event
  public void SendTheEvent()
  {
    Console.WriteLine("We fire the event here: SendTheEvent()");
    this.issueEvent(new EventArgs());
  }
}

Using the code (EventSubscriber.cs)

  1. Add another class.
  2. Change the default .cs name to EventSubsriber.cs.
  3. Copy the code below (be sure to read the comments as we go on).
C#
using System;
/// <summary>
/// Summary description for EventSubscriber.
/// </summary>

public class EventSubscriber
{
  public EventSubscriber()
  {
      //We perform the event subscription here in the Start()..
      this.Start();
  }
 
  static void Main()
  {
      //Create an instance of this class
      EventSubscriber theClass = new EventSubscriber();
  }


  private void Start()
  {
      //We create an instance of the EventPublisher
      EventPublisher theClass3 = new EventPublisher();
      //Here (in simple English), we (this class) want to subscribe to this
      //event delegate (EventDelegate) of EventPublisher. So if the EventPublisher
      //raises any event, please send the event to our method this_OnProgress...
      theClass3.myEvent += new EventPublisher.EventDelegate(this_OnProgress);
      //Here is where the event fires...
      //Lets say u're making an email notification program...
      //So when an email arrives, this (or some other class, in real life),
      //calls the EventPublisher's SendTheEvent method
      theClass3.SendTheEvent();
  }

  private void this_OnProgress( object sender, EventArgs e)
  {
      //Your event handler code goes here
      //We could play the infamous "mail arrived" sound here
      Console.WriteLine("Event handled in this_OnProgress of EventSubscriber");
      //Our sender object gives us some info...
      //In your real app, you would read the EventArgs, for example
      Console.WriteLine("Sender:" + sender.ToString());
  }
}

Run It! (Conclusion)

  1. Build the solution. You will be prompted to set the startup object, just do so.
  2. As you're waiting, note these points:
    • Looks familiar to delegated methods, huh? Of course, it's on the same concept. A method invocation can be also called an 'event', and the method that actually 'runs' is the event handler or subscriber!
    • Our delegate here can be called a multicast delegate, since we can kind of "multicast" our advertisement for the event offered. This means many subscribers may implement the event advertised.
  3. You're done!

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
Malaysia Malaysia
The author has been developing software on a freelance basis and is currently employed by a consulting firm, having just finished his Bsc in Computing (Uni. of Staffordshire, UK). He is residing in Asia and holds among other qualifications, the MCSD.net and MCAD.net charter membership. He has a deep interest in the .Net platform. His previous exposure was in Java. One of his biggest 'concerns' is that one day the world might be blown off orbit by some mad scientist...
NOTE: The author apologises for looking very scary. He's not, in real life...

oMCSD (.Net) Charter member
oMCAD (.Net) Charter member
oMCSE (Microsoft Windows 2000)
oMCSA (Microsoft Windows 2000)
oMCDBA (Microsoft SQL 2000)
oMicrosoft Certified Professional


Comments and Discussions

 
GeneralRecommended if you are learning about delegates and events! Pin
Vruggim22-Feb-11 8:27
Vruggim22-Feb-11 8:27 
GeneralMy vote of 4 Pin
hurricanepv18-Jan-11 8:49
hurricanepv18-Jan-11 8:49 
GeneralThanks Pin
ericmaroudas12-Jan-06 10:39
ericmaroudas12-Jan-06 10:39 
GeneralDude Pin
Anonymous29-Mar-04 21:31
Anonymous29-Mar-04 21:31 
GeneralRe: Dude Pin
DeepStar4-May-04 7:12
DeepStar4-May-04 7:12 
GeneralUnsubscribed Events Pin
CSharpDavid25-Jun-03 8:04
CSharpDavid25-Jun-03 8:04 
GeneralRe: Unsubscribed Events Pin
Daniel Ang Chee Meng25-Jun-03 17:21
Daniel Ang Chee Meng25-Jun-03 17:21 

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.