Part 39 - C# Tutorial - Multicast Delegates

Click here for the article related to Delegates Example Part I
Click here for the article related to Delegates Example Part II
Part 39 - C# Tutorial - Multicast Delegates


A Multicast delegate is a delegate that has references to more than one function. When you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.



There are 2 approaches to create a multicast delegate.


Approach 1: 
using System;
namespace Sample
{
    public delegate void SampleDelegate();
    
    public class Sample
    {
        static void Main()
        {
            SampleDelegate del1 = new SampleDelegate(SampleMethodOne);
            SampleDelegate del2 = new SampleDelegate(SampleMethodTwo);
            SampleDelegate del3 = new SampleDelegate(SampleMethodThree);
            // In this example del4 is a multicast delegate. You use +(plus) 
            // operator to chain delegates together and -(minus) operator to remove.
            SampleDelegate del4 = del1 + del2 + del3 - del2;
            
            del4();
        }


        public static void SampleMethodOne()
        {
            Console.WriteLine("SampleMethodOne Invoked");
        }


        public static void SampleMethodTwo()
        {
            Console.WriteLine("SampleMethodTwo Invoked");
        }


        public static void SampleMethodThree()
        {
            Console.WriteLine("SampleMethodThree Invoked");
        }
    }
}

Approach 2:
using System;
namespace Sample
{
    public delegate void SampleDelegate();
    
    public class Sample
    {
        static void Main()
        {
            // In this example del is a multicast delegate. You use += operator 
            // to chain delegates together and -= operator to remove.
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;
            del += SampleMethodThree;
            del -= SampleMethodTwo;
            
            del();
        }


        public static void SampleMethodOne()
        {
            Console.WriteLine("SampleMethodOne Invoked");
        }


        public static void SampleMethodTwo()
        {
            Console.WriteLine("SampleMethodTwo Invoked");
        }


        public static void SampleMethodThree()
        {
            Console.WriteLine("SampleMethodThree Invoked");
        }
    }
}


Note: A multicast delegate, invokes the methods in the invocation list, in the same order in which they are added.


If the delegate has a return type other than void and if the delegate is a multicast delegate, only the value of the last invoked method will be returned. Along the same lines, if the delegate has an out parameter, the value of the output parameter, will be the value assigned by the last method.


Example: Multicast delegate with an int return type
using System;
namespace Sample
{
    // Deletegate's return type is int
    public delegate int SampleDelegate();
    
    public class Sample
    {
        static void Main()
        {
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;


            // The ValueReturnedByDelegate will be 2, returned by the SampleMethodTwo(),
            // as it is the last method in the invocation list.
            int ValueReturnedByDelegate = del();


            Console.WriteLine("Returned Value = {0}", ValueReturnedByDelegate);
        }


        // This method returns one
        public static int SampleMethodOne()
        {
            return 1;            
        }


        // This method returns two
        public static int SampleMethodTwo()
        {
            return 2;
        }
    }
}


Example: Multicast delegate with an integer output parameter.
using System;
namespace Sample
{
    // Deletegate has an int output parameter
    public delegate void SampleDelegate(out int Integer);
    
    public class Sample
    {
        static void Main()
        {
            SampleDelegate del = new SampleDelegate(SampleMethodOne);
            del += SampleMethodTwo;


            // The ValueFromOutPutParameter will be 2, initialized by SampleMethodTwo(),
            // as it is the last method in the invocation list.
            int ValueFromOutPutParameter = -1;
            del(out ValueFromOutPutParameter);


            Console.WriteLine("Returned Value = {0}", ValueFromOutPutParameter);
        }


        // This method sets ouput parameter Number to 1
        public static void SampleMethodOne(out int Number)
        {
            Number = 1;
        }


        // This method sets ouput parameter Number to 2
        public static void SampleMethodTwo(out int Number)
        {
            Number = 2;
        }
    }
}


Where do you use multicast delegates? This is a very common interview question.
Answer: Multicast delegate makes implementation of observer design pattern very simple. Observer pattern is also called as publish/subscribe pattern.

7 comments:

  1. hey venkat your videos are very helpful could you please upload some videos for 'events using delegates'

    ReplyDelete
  2. Hello I am greatly impressed with your videos, thank you very much for it. According to your videos all functions the delegate is pointing to are invoked. What will happen when 2th function int the list fails. The delegate will continue nevertheless? Does the delegate wait for the first function to be finished to invoke the next one?

    ReplyDelete
  3. Nonetheless, values can be saved from one function call to the next by passing parameters by reference (ref keyword instead of out). So if the delegate signature is :
    public delegate void SampleDelegate(ref int Number);
    and if the functions SampleMethodOne and Two contain Number += 1; then Number will be incremented from one function to the next. This is also true when passing objects from one function to the next.

    ReplyDelete
  4. Hello Venkat. Your tutorial is awesome. May Allah bless you with Good. Can you please tell me why you'd initialize the ValueFromOutputParameter value to -1, instead of 0? What's the purpose and advantage of intializing a variable to -1?

    ReplyDelete
  5. Hi Venkat,
    The concept of Multicast Delegate is very well explained.
    Can you upload videos for Design Patterns? Please make some time & upload videos on these. This is also one of the commonly asked interview question.

    ReplyDelete
  6. Hi Venkat
    first of all many many thanks for your tutotial .. my query where could i find lessones About (ref and out)
    once again thanks a lot

    ReplyDelete

It would be great if you can help share these free resources