Monday, October 27, 2014

Delegates and Events

Events in C# are implemented with delegate. In Event delegate scenario there are two class involved. Publisher class and subscriber class. Publisher class define a delegate. And subscribing class create a method that matches the signature of the delegate. Then it create an instance of that delegate type and encapsulate the method with it. When the event is raised the subscriber class  method is invoked through that delegate.
 
Lets take a simple example. Create a delegate mydelegate with void return type and a single string parameter.
 
public delegate void mydelegate(string s); 

 
Next step is to create and publisher class. Here we create a class named ABC.
 
    class ABC
    {
        public event mydelegate myevent;
        private string _Message;
        public string Message
        {
            get
            {
                return _Message;
            }
            set
            {
                _Message = value;
                myevent(value);
            }
        }
    }

 
In this class we create an event myevent with mydelegate type. And call this event at the time of setting the property and we are done.
 
Now we need to create subscriber class. In this class create a method for delegate type mydelegate. In this example I have created the EventEvent method. Then the final thing. Create and object of class ABC and encapsulate this method with the event myevent.

        ABC a = new ABC();
        a.myevent += new mydelegate(EventEvent);

        public static void EventEvent(string s)
        {
            Console.WriteLine("New Message inserted : " + s);
        }

Build and run the program. The event will raised with the help of delegate at the time of assigning the value for Message property of class ABC.

Output :
-Start program-
New Message inserted : Welcome to event delegate


The complete program is listed below

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

namespace TestDelegate
{
    public delegate void mydelegate(string s);
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("-Start program-");
            ABC a = new ABC();
            a.myevent += new mydelegate(EventEvent);
            a.Message = "Welcome to event delegate" + Environment.NewLine;
            Console.ReadKey();
        }

        public static void EventEvent(string s)
        {
            Console.WriteLine("New Message inserted : " + s);
        }
    }

    class ABC
    {
        public event mydelegate myevent;
        private string _Message;
        public string Message
        {
            get
            {
                return _Message;
            }
            set
            {
                _Message = value;
                myevent(value);
            }
        }
    }
}


Happy Coding .... :)