multicast delegate

Multicast Delegate

  • A Multicast delegate is delegate which has references to more than one function.
  • When we invoke a multicast delegate, all function the delegate is pointing to, are invoked.
  • A multicast delegate, invoke the methods in same order in which they are added.
  • We can register a method with a delegate using + OR += operator.
  • We can un-register a method with from a delegate using – OR -= operator.

Example:

namespace d2cMulticastDelegateSample
{
class Program
{
public delegate void d2cDelegateObj();
static void Main(string[] args)
{
d2cDelegateObj delObj1 = new d2cDelegateObj(d2cMethodOne);
d2cDelegateObj delObj2 = new d2cDelegateObj(d2cMethodTwo);
d2cDelegateObj delObj3 = new d2cDelegateObj(d2cMethodThree);
d2cDelegateObj delObj4;

//register delegate using + operator
delObj4 = delObj3 + delObj1 + delObj2;// register a method with a delegate
Console.WriteLine("Multicast Delegate after register method with + operator");
delObj4();
// invoke the methods in same order in which they are added
Console.WriteLine("\n\nMulticast Delegate after un-register method with -= operator");
delObj4 -= delObj2;
delObj4();
Console.ReadLine();
}

public static void d2cMethodOne()
{
Console.WriteLine("Method One, Welcome to desire2code.com ");
}
public static void d2cMethodTwo()
{
Console.WriteLine("Method Two, Welcome to desire2code.com ");
}
public static void d2cMethodThree()
{
Console.WriteLine("Method Three, Welcome to desire2code.com ");
}
}
}

Output:

Multicast Delegate after register methos with + operator
Method Three, Welcome to desire2code.com
Method One, Welcome to desire2code.com
Method Two, Welcome to desire2code.com

Multicast Delegate after un-register methos with -= operator
Method Three, Welcome to desire2code.com
Method One, Welcome to desire2code.com

  • A 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.

Example:

public delegate string d2cDelegateObj();
static void Main(string[] args)
{
d2cDelegateObj delObj1 = new d2cDelegateObj(d2cMethodOne);
d2cDelegateObj delObj2 = new d2cDelegateObj(d2cMethodTwo);
d2cDelegateObj delObj3 = new d2cDelegateObj(d2cMethodThree);
d2cDelegateObj delObj4;

//register delegate using + operator
delObj4 = delObj3 + delObj1 + delObj2; // register a method with a delegate
Console.WriteLine("Multicast Delegate after register method with + operator");
Console.WriteLine(delObj4());
// Because delObj2 added at last so this multicast delegate invoked function and return delObj2 return value
Console.ReadLine();
}

public static string d2cMethodOne()
{
return "Method One";
}
public static string d2cMethodTwo()
{
return "Method Two";
}
public static string d2cMethodThree()
{
return "Method Three";
}

Output:

Multicast Delegate after register method with + operator
Method Two