Wednesday, October 15, 2014

Multicast Delegates

Multicast Delegates is an useful property of delegate object is to assign multiple objects into a single delegate object. The + operator is used to combine delegates. Same types of delegated can be combined. The multicast delegate contains a list of delegate which is called invocation list. When a multicast delegate is called it invoke delegates from the list in order.






















    public class Example_MulticastDelegate
    {
        public delegate void mydel(string s);

        static void Main(string[] args)
        {
            mydel del = new mydel(Method1);
            del += new mydel(Method2);
            del("Multicast Delegate");
            Console.ReadLine();
        }

        public static void Method1(string s)
        {
            Console.WriteLine("Hello " + s + " I am Method 1.");
        }
        public static void Method2(string s)
        {
            Console.WriteLine("Hello " + s + " I am Method 2.");
        }
    }
In the above program we have two methods, Method1 and Method2. And our objective is to call both methods with a single delegate.

Very first we declare a delegate mydel with void return type and a string parameter.

public delegate void mydel(string s);

Now we need to create an object of delegate mydel and assign Method1 and Method2 into its invocation list.

mydel del = new mydel(Method1);
del += new mydel(Method2);

Finally we need to call our method with the delegate mydel.

del("Multicast Delegate");

Output : 
Hello Multicast Delegate I am Method 1.
Hello Multicast Delegate I am Method 2.


Happy Coding....