Tuesday, June 21, 2011

Delegates And Events in .NET

Today I was working on a project which required the use of 'delegates'. I wanted to see the difference in calling a function using delegates and by events; so created a simple example to show the difference in invoking methods using events and delegates.

Delegates are function pointers in .net. The advantage of using delegates is that the calling program can define the function for a specific task. For example, let us consider the logging of message or exceptions in an application. We can just expose a delegate with signature “public delegate void LogMessage (string msg);” and the calling program can decide whether to do the logging in file or database or to display in console/UI.

An event is a message sent by an object to signal the occurrence of an action.Events are raised in response of an user action or it could be program triggered. It normally has the sender and event arguments as input parameters. But for the example below, I am comparing delegate and event calls and not using sender/event argument parameters



1) Create a console application in .NET (C#).

2) Create a delegate as given below in 'Program.cs'

public delegate void LogMessage(string msg);


3) Create a class (DelegateTestClass) for delegate test

public class DelegateTestClass
    {
        public LogMessage MessageLogger { get; set; }

        public void PerformTask1()
        {
            MessageLogger("Performing Task1");
        }

        public void PerformTask2()
        {
            MessageLogger("Performing Task2");
        }
    }

4) Create a class for Event test as given below

class EventTestClass
    {
        public event LogMessage MessageLogger;

        public void PerformTask1()
        {
            MessageLogger("Performing Task1");
        }

        public void PerformTask2()
        {
            MessageLogger("Performing Task2");
        }
    }

5) In “Program.cs” create a function to handle the delegate and event

private static void ShowMessage(string strMsg)
        {
            Console.WriteLine(strMsg);
        }

6) Now call the event and delegate from ‘Main’ as given below

static void Main(string[] args)
        {
            DelegateTestClass oDelegateTest = new DelegateTestClass();
            /*Specify the function to handle the message logging*/
            oDelegateTest.MessageLogger = new LogMessage(ShowMessage);

            oDelegateTest.PerformTask1();
            oDelegateTest.PerformTask2();


            EventTestClass oEventTest = new EventTestClass();
            /*Attach function to the event*/
            oEventTest.MessageLogger += new LogMessage(ShowMessage);

            oEventTest.PerformTask1();
            oEventTest.PerformTask2();

            Console.ReadLine();
        }

1 comment:

Unknown said...

Great blog..Keep up the good and simple work..

Thanks for your valuable help to the community.