What is multicast delegate in C#?

Technology CommunityCategory: C#What is multicast delegate in C#?
VietMX Staff asked 3 years ago

Delegate can invoke only one method reference has been encapsulated into the delegate. It is possible for certain delegate to hold and invoke multiple methods. Such delegate called multicast delegate. Multicast delegate also know as combinable delegate, must satisfy the following conditions:

  • The return type of the delegate must be void. None of the parameters of the delegate type can be delegate type can be declared as output parameters using out keywords.
  • Multicast delegate instance is created by combining two delegates, the invocation list is formed by concatenating the invocation list of two operand of the addition operation. Delegates are invoked in the order they are added.

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.)

Consider:

ublic partial class MainPage : PhoneApplicationPage
{
    public delegate void MyDelegate(int a, int b);
    // Constructor
    public MainPage()
    {
        InitializeComponent();

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

}