Saturday, January 12, 2013

What is a multicast delegate in C#?



Multicast delegate

A delegate which holds the reference of multiple methods is called multicast delegate . And simple delegates hold the reference of only single method. When you invoke the multicast delegate, all the reference methods are called.

Example

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

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

    public class Operatinos
    {
        public delegate void Notification(string str);
        Notification SendNotification;

        LogFileNotification logFileNotification = null;
        EmailNotification emailNotification = null;

        //Constructor
        public Operatinos()
        {
            logFileNotification = new LogFileNotification();
            emailNotification = new EmailNotification();

            SendNotification += logFileNotification.WriteLog;
            SendNotification += emailNotification.SendEmail;
        }

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

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

            Console.ReadLine();
        }
    }
       

Output

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

No comments:

Post a Comment