Multicast Delegates in C#

Multicast Delegates in C# with Examples

In this article, I am going to discuss the Multicast Delegates in C# with Examples. Please read our previous article where we discussed Single Cast Delegates in C# with examples. As part of this article, we are going to discuss the following pointers in detail.

  1. What is Multicast Delegate in C#?
  2. How to create Multicast Delegates in C#?
  3. Different ways to create Multicast Delegates.
  4. Multicast Delegate with Return Type in C#.
  5. Multicast Delegate with Output Parameter in C#.
What is Multicast Delegate in C#?

A Multicast Delegate in C# is a delegate that holds the references of more than one function. When we invoke the multicast delegate, then all the functions which are referenced by the delegate are going to be invoked. If you want to call multiple methods using a delegate then all the method signatures should be the same.

Example: Multicast Delegate in C#

Let us see an example for understanding the Multicast Delegate in C#. Please have a look at the following example which is without using delegates. In the below example, we created two methods, and then from the main method, we are creating the instance of the class and then invoke the two methods.

namespace MulticastDelegateDemo
{
    public class Rectangle
    {
        public void GetArea(double Width, double Height)
        {
            Console.WriteLine(@"Area is {0}", (Width * Height));
        }
        public void GetPerimeter(double Width, double Height)
        {
            Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
        }
        static void Main(string[] args)
        {
            Rectangle rect = new Rectangle();
            rect.GetArea(23.45, 67.89);
            rect.GetPerimeter(23.45, 67.89);
            Console.ReadKey();
        }
    }
}
Output:

What is Multicast Delegate in C#?

In the above example, we created an instance of the Rectangle class and then called the two methods. Now I want to create a single delegate that is going to invoke the above two methods (i.e. GetArea and GetPerimeter). The two methods having the same signature with the different method names, so we can create a single delegate that holds the reference of the above two methods. And when we invoke the delegate, it is going to invoke the above two methods. And when we do so, then it is called a Multicast Delegate.

Example: Multicast Delegate in C#.

In the below example, we have created one delegate whose signature is the same as the two methods i.e. GetArea and GetPerimeter. Then we created the instance of delegate and bind the two methods using the += operator. Similarly, you can use the -= operator to remove a function from the delegate. Once we bind the two methods with the delegate instance and then when we call the delegate, both methods are going to be executed.

namespace MulticastDelegateDemo
{
    public delegate void RectangleDelete(double Width, double Height);
    public class Rectangle
    {
        public void GetArea(double Width, double Height)
        {
            Console.WriteLine(@"Area is {0}", (Width * Height));
        }
        public void GetPerimeter(double Width, double Height)
        {
            Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
        }
        static void Main(string[] args)
        {
            Rectangle rect = new Rectangle();
            RectangleDelete rectDelegate = new RectangleDelete(rect.GetArea);
            //RectangleDelete rectDelegate = rect.GetArea;

            //binding a method with delegate object
            // In this example rectDelegate is a multicast delegate. You use += operator 
            // to chain delegates together and -= operator to remove.

            rectDelegate += rect.GetPerimeter;
            rectDelegate(23.45, 67.89);

            Console.WriteLine();
            rectDelegate.Invoke(13.45, 76.89);

            Console.WriteLine();
            //Removing a method from delegate object
            rectDelegate -= rect.GetPerimeter;
            rectDelegate.Invoke(13.45, 76.89);

            Console.ReadKey();
        }
    }
}
Output:

How to create Multicast Delegates in C#?

Another approach to Create Multicast Delegates in C#.

Here in the below example, I am going to show you the use of both static and non-static methods along with different ways to create and invoke multicast delegates. Please have a look at the below example. Here, we created one delegate which takes two integer parameters and returns nothing. Then within the program class, we define four methods and all these four methods take two integer parameters and return nothing i.e. void. Then we created four instances of the delegate and bind the four methods. Finally, we create the fifth delegate instance and to this instance, we are binding all the four delegate instances using the + operator. Now, the fifth delegate becomes a multicast delegate. And when we invoke the fifth delegate instance then all the four methods are going to be executed. If you want to remove one method binding, then simply you need to use the -= operator and specify the delegate instance which you want to remove.

namespace MulticastDelegateDemo
{
    public delegate void MathDelegate(int No1, int No2);

    public class Program
    {
        public static void Add(int x, int y)
        {
            Console.WriteLine("THE SUM IS : " + (x + y));
        }
        public static void Sub(int x, int y)
        {
            Console.WriteLine("THE SUB IS : " + (x - y));
        }
        public void Mul(int x, int y)
        {
            Console.WriteLine("THE MUL IS : " + (x * y));
        }
        public void Div(int x, int y)
        {
            Console.WriteLine("THE DIV IS : " + (x / y));
        }
        
        static void Main(string[] args)
        {
            Program p = new Program();
            MathDelegate del1 = new MathDelegate(Add);
            MathDelegate del2 = new MathDelegate(Program.Sub);
            MathDelegate del3 = p.Mul;
            MathDelegate del4 = new MathDelegate(p.Div); ;

            //In this example del5 is a multicast delegate. We can use +(plus) 
            // operator to chain delegates together and -(minus) operator to remove.
            MathDelegate del5 = del1 + del2 + del3 + del4;
            del5.Invoke(20, 5);
            Console.WriteLine();
            del5 -= del2;
            del5(22, 7);
            
            Console.ReadKey();
        }
    }
}
Output:

Different ways to create Multicast Delegates.

Multicast Delegates with Return Type in C#:

A multicast delegate invokes the methods 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, then 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 invoked method.

Example: Multicast Delegates with Return Type in C#

Let’s understand Multicast Delegates with Return Type in C# with an example. Please have a look at the below example. Here, we created one delegate which does not take any parameter but its return type is int. Then we created two static methods and the first static method returns 1 and the second static method returns 2. Then we created the delegate instance and first bind Method one and second bind method two. And when we invoke the delegate, the first MethodOne is executed and then MethodOne is executed and it returns 2 as the last invoked method is MethodTwo which returns 2.

namespace MulticastDelegateDemo
{
    // Deletegate's return type is int
    public delegate int SampleDelegate();
    public class Program
    {
        static void Main()
        {
            SampleDelegate del = new SampleDelegate(MethodOne);
            del += MethodTwo;

            // The ValueReturnedByDelegate will be 2, returned by the MethodTwo(),
            // as it is the last method in the invocation list.
            int ValueReturnedByDelegate = del();
            Console.WriteLine("Returned Value = {0}", ValueReturnedByDelegate);

            Console.ReadKey();
        }
        // This method returns one
        public static int MethodOne()
        {
            return 1;
        }

        // This method returns two
        public static int MethodTwo()
        {
            return 2;
        }
    }
}
Output:

Multicast Delegate with Return Type in C#.

Multicast Delegates with out parameter in C#.

Now we will see an example of Multicast delegate in C# with out parameter. Please have a look at the below example. Here, we created one delegate which takes one out parameter and returns nothing i.e. void. Then we created two static methods and both the static methods take one out parameter. The first static method assigning 1 value to the out parameter and the second static assigns value 2 to the out parameter. Then we created the delegate instance and first bind MethodOne and second bind MethodTwo. And when we invoke the delegate, first MethodOne is executed and then MethodOne is executed and it returns 2 as the last invoked method is MethodTwo which assigns value 2 to the out parameter.

namespace MulticastDelegateDemo
{
    // Deletegate has an int output parameter
    public delegate void SampleDelegate(out int Integer);

    public class Program
    {
        static void Main()
        {
            SampleDelegate del = new SampleDelegate(MethodOne);
            del += MethodTwo;

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

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

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

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

Multicast Delegate with Output Parameter in C#.

That’s it for today. In the next article, I am going to discuss one real-time example of using delegates. Here, In this article, I try to explain Multicast Delegates in C# with examples. I hope you enjoy this article and understand the need and use of Multicast Delegates in C# woth Examples. 

3 thoughts on “Multicast Delegates in C#”

  1. blank

    In del multicasting what if one method is retuning void and one is returning some value ? E.g. del = new del(methodReturnInt); del += methodReturnVoid; del();

    1. blank

      basic Definition of Delegate states that its type safe function pointer so both the functions signatures should be match we can’t implement
      del = new del(methodReturnInt); del += methodReturnVoid; del();

Leave a Reply

Your email address will not be published. Required fields are marked *