Friday 13 May 2011

Delegates and Events

Delegates

Delegate is pointer to function. In other way we can say that delegate holds the reference of the function. Instead of calling the function we calling the delegate. Signature of the delegate and signature function should be same. In below example we declare delegate which is not taking any parameter and not returning any value. After understanding delegate I am listing benefits of delegate.

Code Example

namespace BasicDelegate
{

    // Declaration
    public delegate void MyDelegate();


    class DelegateExample
    {
        public static void MyFunction()
        {
            Console.WriteLine("I was called by delegate ...");
        }


        static void Main(string[] args)
        {
            MyDelegate myDelegate = new MyDelegate(MyFunction);
            myDelegate();
            Console.ReadLine();

        }
    }
}


Events

The basic of the event is publisher and subscriber.  Publishers object publish event and any number of object can be subscribe to publisher object. To declare event first we have to declare a delegate. By using delegate event should be declared. In below example we have publisher class which is publishing the event and subscriber class is Program.

Code Example

Main Method
class Program
    {
        //This is simple method which will write into console
        static void Logger(string s)
        {
            Console.WriteLine(s);
        }

        static void Main(string[] args)
        {
            FileLoggerClass fl = new FileLoggerClass("process.log");
            PublisherClass publisherClass = new PublisherClass();

            // Subscribe the Functions Logger and fl.Logger
            publisherClass.Log += new PublisherClass.LogHandler(Logger);
            publisherClass.Log += new PublisherClass.LogHandler(fl.LoggerMethod);

            // The Event will now be triggered in the Process() Method
            publisherClass.Process();

            fl.Close();

        }
    }


Publisher Class
class PublisherClass
    {
        public delegate void LogHandler(string message);
        // Define an Event based on the above Delegate
        public event LogHandler Log;
        // Instead of having the Process() function take a delegate
        // as a parameter, we've declared a Log event. Call the Event,
        // using the OnXXXX Method, where XXXX is the name of the Event.
        public void Process()
        {
            OnLog("Process() begin");
            OnLog("Process() end");
        }
        // By Default, create an OnXXXX Method, to call the Event
        protected void OnLog(string message)
        {
            if (Log != null)
            {
                Log(message);
            }
        }
    }

Simple File logger class

class FileLoggerClass
    {
        FileStream fileStream;
        StreamWriter streamWriter;

        // Constructor
        public FileLoggerClass(string filename)
        {
            fileStream = new FileStream(filename, FileMode.Create);
            streamWriter = new StreamWriter(fileStream);
        }

        // Member Function which is used in the Delegate
        public void LoggerMethod(string s)
        {
            streamWriter.WriteLine(s);
        }

        public void Close()
        {
            streamWriter.Close();
            fileStream.Close();
        }

    }

No comments:

Post a Comment