A multicast delegate is an instance of a delegate that can point to more than one method. When a multicast delegate is invoked, all the methods pointed to by the delegate are executed in order.
This capability allows executing multiple methods in response to a single event or action.
In fact, in C# all delegates are multicast delegates. We just have to use them in a slightly different way.
Multicast Delegate Syntax
Multicast delegates are created by combining instances of delegates using the +
operator or the Delegate.Combine
method.
DelegateType multicastDelegate = MyDelegate1 + MyDelegate2;
However, in general, it is common to use +=
to combine delegates “in situ”.
Basic Example
We can see this better with an example. Let’s suppose we have two methods, Method1
and Method2
, both of which receive a string
. On the other hand, we have a definition of MyDelegate
that matches the signature of these methods.
We can create an instance of MyDelegate
called multicastDelegate
that executes both methods by creating two delegates and combining them with +
.
static void Method1(string message)
{
Console.WriteLine("Method1: " + message);
}
static void Method2(string message)
{
Console.WriteLine("Method2: " + message);
}
delegate void MyDelegate(string message);
MyDelegate delegate1 = new MyDelegate(Method1);
MyDelegate delegate2 = new MyDelegate(Method2);
MyDelegate multicastDelegate = delegate1 + delegate2;
multicastDelegate("Hello World");
// Output:
// Method1: Hello World
// Method2: Hello World
However, as I mentioned, it is common to use +=
to combine them directly. This would be done like this:
MyDelegate multicastDelegate = Method1;
multicastDelegate += Method2;
This is equivalent to the creation of the previous multicastDelegate
, without the need to create delegate1
and delegate2
. It is the syntax you will commonly use, but it’s good to see how it works “under the hood”.
Unsubscribing a Method
It is also possible to unsubscribe a method that we have included in a multicast delegate. For this, we can use the -
operator or the Delegate.Remove
method.
MyDelegate multicastDelegate2 = multicastDelegate - delegate1;
For this, similarly to the case of delegate combination, it is common to use the -=
operator directly.
We can see it more easily with an example. In the previous case,
// this is what we had
MyDelegate multicastDelegate = Method1;
multicastDelegate += Method2;
// now I remove Method1 from the delegate
multicastDelegate -= Method1;
multicastDelegate("Hello World");
// Output:
// Method2: Hello World
In this case, it would only call Method2
, because we have removed Method1
from the delegate.
This is a very common practice when we see events, because sometimes we will want to stop listening to them temporarily or permanently.