A multidelegate is an instance of a delegate that can point to more than one method. When a multidelegate is invoked, all the methods pointed by the delegate are executed in order.
This ability allows you to execute multiple methods in response to a single event or action.
In fact, in C# all delegates are multidelegates. We just have to use them slightly differently.
Multidelegate syntax
Multidelegates are created by combining delegate instances using the +
operator or the Delegate.Combine
method.
DelegateType multidelegate = MyDelegate1 + MyDelegate2;
Although, in general, we usually use +=
to combine delegates “in-place”.
Basic example
We can see it better with an example. Let’s suppose we have two methods, Method1
and Method2
, both receiving a string
. On the other hand, we have a MyDelegate
definition that matches the signature of these methods.
We can create an instance of MyDelegate
called multidelegate
that executes both methods, creating two delegates and combining them with +
.
static void Method1(string message)
{
Console.WriteLine("Method1: " + message);
}
static void Method2(string message)
{
Console.WriteLine("Method1: " + message);
}
delegate void MyDelegate(string message);
MyDelegate delegate1 = new MyDelegate(Method1);
MyDelegate delegate2 = new MyDelegate(Method2);
MyDelegate multidelegate = delegate1 + delegate2;
multidelegate("Hello World");
// Output:
// Method1: Hello World
// Method2: Hello World
However, as I said before, the usual thing is to use +=
to combine them directly. This would be done as follows:
MyDelegate multidelegate = Method1;
multidelegate += Method2;
This is equivalent to the creation of the previous multidelegate
, without the need to create delegate1
and delegate2
. It is the syntax that you will usually use, but it is good to see how it works “under the hood”.
Unlink a method
It is also possible to unlink a method that we have included in a multidelegate. For this, we can use the -
operator or the Delegate.Remove
method.
MyDelegate multidelegate2 = multidelegate - delegate1;
For this, similarly to the delegate combination case, the usual thing is to use the -=
operator directly.
We see it easier with an example. In the previous case,
// this is what we had
MyDelegate multidelegate = Method1;
multidelegate += Method2;
// now I remove Method1 from the delegate
multidelegate -= Method1;
multidelegate("Hello world");
// Output:
// Method2: Hello World
In this case, it would call only 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 definitively.