What are multicasting delegates in C#?

CsharpProgrammingServer Side Programming

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);
raja
Published on 13-Aug-2018 08:41:59
Advertisements