Am studying about delegates. As I read. I learned that adding more than one function in a delegate is called multicast delegate. Based on that I wrote a program. Here two functions (AddNumbers and MultiplyNumbers) I added in the MyDelegate. Is the below program is an example for multicast delegate ?.
public partial class MainPage : PhoneApplicationPage
{
public delegate void MyDelegate(int a, int b);
// Constructor
public MainPage()
{
InitializeComponent();
MyDelegate myDel = new MyDelegate(AddNumbers);
myDel += new MyDelegate(MultiplyNumbers);
myDel(10, 20);
}
public void AddNumbers(int x, int y)
{
int sum = x + y;
MessageBox.Show(sum.ToString());
}
public void MultiplyNumbers(int x, int y)
{
int mul = x * y;
MessageBox.Show(mul.ToString());
}
}
Actually all delegates in C# are MulticastDelegates, even if they only have a single method as target. (Even anonymous functions and lambdas are MulticastDelegates even though they by definition have only single target.)
MulticastDelegate
is simply the base class for all kinds of function or method references in C#, whether they contain one or more targets.So this:
Sets
myDel
to aMulticastDelegate
with a single target. But this line:Updates
myDel
to aMulticastDelegate
with two targets.Yes, it's an example of a multicast delegate. Note that instead of
you can typically say just
because a so-called method group conversion exists that will create the delegate instance for you.
Another thing to note is that your declaration
public delegate void MyDelegate(int a, int b);
does not have to reside inside another type (here inside theMainPage
class). It could be a direct member of the namespace (since it's a type). But of course it's perfectly valid to "nest" it inside a class, as you do, for reasons similar to the reason why you create nested classes.Multicast delegates is one of the feature of delegates, it wraps the reference of multiple methods and calls it sequentially and it is also known as Delegate Chaining.
Below is the example of multicast delegates.