Sunday, January 6, 2013

Difference between Delegate and Events in C#?

Delegate:

A delegate in C# is similar to a function pointer in C. A delegate object holds the reference of one or more methods. Delegate creation is the four steps process.

  • Declaration of delegate
  • Delegate object creation
  • Point the reference to the method.
  • Invoke delegate

A delegate object doesn't care about the class in which the function exists. There is only one restriction that the delegate signature and the function signature should be same otherwise delegate object can’t hold the reference of the method which doesn't have the same signature. Signature means return type and parameters.

Example
public class Math
    {
        public static int Add(int i, int j)
        {
            return i + j;
        }
    }

    class DelegateAndEvent
    {
        //Delegate Declaration
        public delegate int MathFunctions(int i, int j);

        static void Main()
        {
            //Delegate object creation.
            MathFunctions MathFun = null;

            //Point the reference to the method.
            MathFun += Math.Add;

           // Invoke delegate.
            int value = MathFun.Invoke(10, 20);
            Console.WriteLine(value.ToString());

            Console.ReadLine();
        }
    }

Events:


Event is a mechanism by which a class can send notification to its client. For example, you have an application to perform certain operation, if an operation is failed then the application send the notification to log file, printer, fax, email etc. 

Events are declared using delegates. Without delegate, we can not create Events.

Example

    //subscriber class
    public class LogFileNotification
    {
        //Constructor 
        public LogFileNotification(Operatinos obj)
        {
            obj.SendNotification += WriteLog;           
        }

        private void WriteLog(string message)
        {
            //Write Log into a file
            Console.WriteLine("WriteLog :- " + message);
        }
    }

    //subscriber class
    public class PrinterNotification
    {
        //Constructor
        public PrinterNotification(Operatinos obj)
        {
            obj.SendNotification += PrintFailure;
        }

        private void PrintFailure(string message)
        {
           // Print the failure text. 
            Console.WriteLine("PrintFailure :- " + message);
        }
    }

    //subscriber class
    public class FaxNotification
    {
        //Constructor
        public FaxNotification(Operatinos obj)
        {
            obj.SendNotification += SendFax;
        }

        private void SendFax(string message)
        {
            // Send Fax to appropriate person.
            Console.WriteLine("SendFax :- " + message);
        }
    }

    //subscriber class
    public class EmailNotification
    {
        //Constructor
        public EmailNotification(Operatinos obj)
        {
            obj.SendNotification += SendEmail;
        }

        public void SendEmail(string message)
        {
            // Send email to appropriate person.
            Console.WriteLine("EmailNotification :- " + message);
        }
    }


    //Publisher class
    public class Operatinos
    {
        public delegate void Notification(string str);
        public event Notification SendNotification;
        LogFileNotification logFileNotification = null;
        PrinterNotification printerNotification = null;
        FaxNotification faxNotification = null;
        EmailNotification emailNotification = null;

       //Constructor
        public Operatinos()
        {
            logFileNotification = new LogFileNotification(this);
            printerNotification = new PrinterNotification(this);
            faxNotification = new FaxNotification(this);
            emailNotification = new EmailNotification(this);
        }

        public void OperationFailed()
        {
            SendNotification("Operation is failed.");
        }
    }

    public class MainClass
    {
        static void Main()
        {
            Operatinos op = new Operatinos();
            op.OperationFailed();

            Console.ReadLine();
        }
    }


Output

WriteLog :- Operation is failed.
PrintFailure :- Operation is failed.
SendFax :- Operation is failed.
EmailNotification :- Operation is failed.

The above example is based on publisher subscription model and we have achieved publisher subscription model through events. But the same things we can also achieved through delegate. Now the question comes, What is the main difference between Delegate and Events?

Main difference between Delegate and Events?

If we create a delegate into publisher class then subscriber has the authority todo the multiple operations on the delegate. It can invoke the delegate; can make the clone of the delegate and other operation also. See the below image.



































But if we create Events into publisher class then subscriber class doesn't has any authority to do the operation. See the below image.




4 comments:

  1. Link for the missing image is :
    http://4.bp.blogspot.com/-RTiktXjP_m8/UOASrAy3w0I/AAAAAAAAAAg/IAWFzuqcy6k/s640/event1.JPG

    ReplyDelete
  2. simple and gr8 exact explanation

    ReplyDelete