Defination:
A Multicast delegate is a delegate that has references to more than one function.
When you call a multicast delegate, all the functions the delegate is pointing to, are invoked.
Example 1:
using System;
namespace demo
{
public delegate void demoDelegate();
public class demoSample
{
static void Main()
{
demoDelegate del1 = new demoDelegate(demoMethodOne);
demoDelegate del2 = new demoDelegate(demoMethodTwo);
demoDelegate del3 = new demoDelegate(demoMethodThree);
demoDelegate del4 = del1 + del2 + del3 - del3;
del4(); // del4 invokes de1 and del2, since -del3 is invoked, call to del3 is removed.
}
public static void demoMethodOne()
{
Console.WriteLine("SampleMethodOne Invoked");
}
public static void demoMethodTwo()
{
Console.WriteLine("SampleMethodTwo Invoked");
}
public static void demoMethodThree()
{
Console.WriteLine("SampleMethodThree Invoked");
}
}
}
Note:
- Delegate objects can be composed using the "+" operator.
- The "-" operator can be used to remove a component delegate from a composed delegate.
- 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.
- If the delegate has an out parameter, the value of the output parameter, will be the value assigned by the last method.
Example 2: Instead of creating multiple delegate object, we can directly assign method through += and -=.
namespace demo
{
public delegate void demoDelegate();
public class demoSample
{
static void Main()
{
demoDelegate del = new demoDelegate(demoMethodOne);
del += demoMethodTwo;
del += demoMethodThree;
del -= demoMethodTwo;
}
public static void demoMethodOne()
{
Console.WriteLine("SampleMethodOne Invoked");
}
public static void demoMethodTwo()
{
Console.WriteLine("SampleMethodTwo Invoked");
}
public static void demoMethodThree()
{
Console.WriteLine("SampleMethodThree Invoked");
}
}
}
Comments
Post a Comment