Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multicast delegate C#

Tags:

c#

delegates

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());
    }

}
like image 249
Arun Avatar asked Dec 20 '22 09:12

Arun


1 Answers

Yes, it's an example of a multicast delegate. Note that instead of

new MyDelegate(AddNumbers)

you can typically say just

AddNumbers

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 the MainPage 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.

like image 198
Jeppe Stig Nielsen Avatar answered Jan 17 '23 23:01

Jeppe Stig Nielsen