What are multicasting delegates in C#?


A delegate that holds a reference to more than one method is called multicasting delegate.

Let us see an example −

Example

using System;
delegate void myDelegate(int val1, int val2);
public class Demo {
   public static void CalAdd(int val1, int val2) {
      Console.WriteLine("{0} + {1} = {2}", val1, val2, val1 + val2);
   }

   public static void CalSub(int val1, int val2) {
      Console.WriteLine("{0} - {1} = {2}", val1, val2, val1 - val2);
   }
}

public class Program {
   static void Main() {
      myDelegate d = new myDelegate(Demo.CalAdd);
      d += new myDelegate(Demo.CalSub);
      d(45, 70);
      d -= new myDelegate(Demo.CalAdd);
      d(95, 70);
      d += new myDelegate(Demo.CalSub);
      d(88, 6);
      d -= new myDelegate(Demo.CalAdd);
      d(40, 20);
      Console.Read();
   }
}

In the above example, our delegate is −

delegate void myDelegate(int val1, int val2);

Using the following, we have set a reference to more than one method in delegates i.e. CalAdd() and CalSub() −

myDelegate d = new myDelegate(Demo.CalAdd);
d += new myDelegate(Demo.CalSub);
d(45, 70);
d -= new myDelegate(Demo.CalAdd);
d(95, 70);
d += new myDelegate(Demo.CalSub);
d(88, 6);
d -= new myDelegate(Demo.CalAdd);
d(40, 20);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements