Explaining Delegates in C# - Part 2 (Events)

by rahul 12/17/2008 3:39:39 AM

In my previous post, I spoke about a few very basic and simple reasons of using delegates - primarily callback. In this post, I'll talk about creating Events using delegates.

I have tried to annotate the class with comments so that it is easy to comprehend. But IMHO, the best way to figure out what's going on is to copy/paste the following code and create breakpoint in the Main() class and hit F11 to step into the code. You will notice that Events are based on the Observer or Publish/Subscribe design pattern.

There are 3 rules which are MANDATORY when you are planning to create events...

Rule 1> The delegate must be defined with two arguments
Rule 2> These arguments always represent TWO objects…
            The Publisher (object that raised the event)
            Event Information object
Rule 3> The 2nd object HAS to be derived from EventArgs

Step through the code and see for yourself how easy this is!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegatesAndEvents
{
    //There are 3 rules which are MANDATORY when you are planning to create events
    //Rule 1> The delegate must be defined with two arguments
    //Rule 2> These arguments always represent TWO objects… 
    //          The Publisher (object that raised the event)
    //          Event Information object
    //Rule 3> The 2nd object HAS to be derived from EventArgs

    //To comply with Rule 3 we create a LoggerEventArgs which is derived from EventArgs
    class LoggerEventArgs : EventArgs
    {
        //constructor to initialize the UserName property
        public LoggerEventArgs(string UserName)
        {
            this.username = UserName;
        }

        string username;
        public string UserName
        {
            get { return username; }
        }
    };

    //To comply with Rule 1 and 2, in the publisher class we created a delegate and event declaration
    class InventoryManager // Publisher
    {
        public delegate void LoggerEventHandler(object source, LoggerEventArgs e);
        public event LoggerEventHandler OnInventoryUpdate;

        //This method will fire an event called OnInventoryUpdate whenever called
        public void LogEvent(string username)
        {
            LoggerEventArgs e = new LoggerEventArgs(username);
            if (OnInventoryUpdate != null)
            {
                Console.WriteLine("LogEvent > Raising events to all subscribers...\n");
                OnInventoryUpdate(this, e);
            }
        }
    };

    class InventoryLogger // Subscriber
    {
        InventoryManager inventoryManager;
        public InventoryLogger(InventoryManager inventoryManager)
        {
            Console.WriteLine("InventoryWatcher > Subscribing to OnInventoryUpdate event...\n");
            this.inventoryManager = inventoryManager;

            //Wiring the event so that the event is fired
            inventoryManager.OnInventoryUpdate += 
new InventoryManager.LoggerEventHandler(OnInventoryUpdate); } void OnInventoryUpdate(object source, LoggerEventArgs e) { Console.WriteLine("The guy who changed this inventory was... " + e.UserName); } } class DelegateEvents { public static void Main() { InventoryManager inventoryManager = new InventoryManager(); Console.WriteLine("Main > Instantiating the subscriber... \n\n"); InventoryLogger inventoryLog = new InventoryLogger(inventoryManager); inventoryManager.LogEvent("Rahul Soni"); Console.ReadLine(); } }; }

In the next post, I will talk about Asynchronous callbacks using delegates.

Cheers, Wave
Rahul


Quote of the day:
The prime purpose of eloquence is to keep other people from talking. - Louis Vermeil


blog comments powered by Disqus

Comments

Search


Tags



Categories

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

All Items
Sign in

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0