Sample Application Event and Delegate

By Devesh Singh Blogs | C# Tutorials Aug 21, 2013
One of the Simplest Example to understand event,delegate,eventargs
Events and delegates..One of the most confusing topics for c# developers,though we get multiple references,different definitions,but yes as a developer intially i always think where do we use that?I have created a sample application and sharing with you guys.
Before diving into sample,lets discuss few basic things related to Event,Delegates and EventArgs.

EventArgs- Eventargs is nothing but the actual data that we pass to subscribers when certain event takes place.The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

Delegate-In C#,we define delegate with Handler suffix.Right,but what is that?For me,its like a pipeline between a certain event raiser and event handler.It  is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method and a class such as a windows control can call your method when a certain event occurs.

But Why do we need it?

the code needing to perform the action doesn't know the method to call when it's written. You can only call the method directly if you know at compile-time which method to call, right? So if you want to abstract out the idea of "perform action X at the appropriate time" you need some representation of the action, so that the method calling the action doesn't need to know the exact implementation ahead of time.


Events - An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).

Events are just properties (like the get;set; properties to instance fields) which expose subscription to the delegate from other objects. These properties, however don't support get;set;. Instead they support add;remove;

So you can have:

 Action myField; public event Action MyProperty {
add { myField += value; }
remove { myField -= value; } }

So lets go through the following sample app and if any issues,do get back to me.


/* Event delegation works on the Publisher <-> Subscriber Model. The Publisher exposes events that clients who are interested can subscribe

 * to and when an event occurs, the subscribers are notified.

 * If we were to consider a common real world example, we could think of implementing a Meeting Scheduler(Outlook) and its Subscibers(Attendee)
 * The code below implements the Scheduler as the Publisher and its Subscribers as Attendee who subscribe to be notified of attending meetings

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

namespace EventDelegate
{
    class Meeting
    {
        static void Main(string[] args)
        {
            //We will first instantiate our Publisher - Which is our Scheduler - eg Outlook
            Scheduler scheduler = new Scheduler();
            
            //Add subscribers
            Attendee Devesh = new Attendee(scheduler,"Devesh");
            Attendee Mukesh = new Attendee(scheduler, "Mukesh");
            Attendee Nisha = new Attendee(scheduler, "Nisha");

            //Scheduler now will get the meeting details for us
            scheduler.getMeetingDetails();
            Console.ReadLine();
        }
    }
    //This is our public delegate that will be hooked up by our subscribers.
    public delegate void MeetingHandler(object sender,MeetingDetailEventArgs e );

    public class Scheduler// Scheduler is our publisher.
    {
        
        public event MeetingHandler meetingNotificationList;
        public void getMeetingDetails()
        {
            Console.WriteLine("Meeting Scheduled.Details are\n");
            MeetingDetailEventArgs e = new MeetingDetailEventArgs("Buddha","Monday");
            if (meetingNotificationList != null)
            {
                meetingNotificationList(this,e);
            }
        }

    }
    public class MeetingDetailEventArgs:EventArgs
    {
       public  string MeetingRoom { get; set; }
       public string MeetingDay { get; set; }
        public MeetingDetailEventArgs(string meetingroom,string meetingday)
        {
            MeetingDay = meetingday;
            MeetingRoom = meetingroom;
        }
    }


    public class Attendee //Instances of this class will be the subscribers of Scheduler
    {
        string AttendeeName { get; set; }
        Scheduler ClientScheduler;
        public Attendee(Scheduler ClientScheduler,string attendeename)
        {
            AttendeeName = attendeename;
            this.ClientScheduler = ClientScheduler;
            ClientScheduler.meetingNotificationList += new MeetingHandler(OnRecevingRequest);

        }
        //This method will be invoked upon a getting MeetingDetails.
        public void OnRecevingRequest(object o, MeetingDetailEventArgs e)
        {
            Console.WriteLine(AttendeeName + " has accepted. Schduled Meeting is in room " + e.MeetingRoom + " on " + e.MeetingDay);
        }
    }

}


Thanks,
Devesh

COMMENT USING