Language: EN

csharp-multidelegados

What is and how to use a multidelegate in C#

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 to by the delegate are executed in order.

This capability allows multiple methods to be executed in response to a single event or action.

In fact, in C# all delegates are multidelegates. We just have to use them in a slightly different way.

Multidelegate Syntax

Multidelegates are created by combining delegate instances using the + operator or the Delegate.Combine method.

DelegateType multidelegate = MyDelegate1 + MyDelegate2;

However, generally, the usual practice is to use += to combine delegates “in-situ”.

Basic Example

We see it better with an example. Let’s suppose we have two methods, Method1 and Method2, both of which take 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 multidelegate 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 multidelegate = delegate1 + delegate2;
multidelegate("Hello World");

// Output:
// Method1: Hello World
// Method2: Hello World

However, as I mentioned earlier, the usual practice is to use += to combine them directly. This would be done like this:

MyDelegate multidelegate = Method1;
multidelegate += Method2;

This is equivalent to the creation of the previous multidelegate, without needing to create delegate1 and delegate2. This is the syntax you will commonly use, but it’s good to see how it works “under the hood”.

Unlinking a Method

It is also possible to unlink a method that we have included in a multidelegate. To do this, we can use the - operator or the Delegate.Remove method.

MyDelegate multidelegate2 = multidelegate - delegate1;

For this, similarly to the case of combining delegates, it is usual to directly use the -= operator.

We see it more easily 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, only Method2 would be called 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.