In C#, a multicast delegate is a type of delegate that can hold references to multiple methods. While regular delegates hold a reference to a single method, multicast delegates can maintain a list of references to multiple methods. When we invoke a multicast delegate, it calls each method in the order they were added. All methods associated with a multicast delegate must have the same signature, meaning they should have the same number and types of parameters. This ensures consistency when the delegate is invoked, and each method in the invocation list receives the same set of arguments.
Let’s learn about how multicast delegates work:
We use the delegate keyword to declare a multicast delegate
, similar to regular delegates, but we can use the +=
operator to combine multiple methods.
delegate void MyDelegate(string message);
In the case above, all methods added to the MyDelegate
multicast delegate must accept a single parameter of type string
. Attempting to add a method with a different parameter type or count will result in a compilation error.
We can add methods with the +=
operator to add them to the delegate’s invocation list.
MyDelegate myDelegate = Method1;myDelegate += Method2;myDelegate += Method3;
In the example above, myDelegate
now holds references to Method1
, Method2
, and Method3
.
When we invoke a multicast delegate
, it calls each method in the order they were added.
myDelegate("Hello, World!");
In this case, it will call Method1
, Method2
, and Method3
with the "Hello, World!"
message.
We can remove methods from a multicast delegate using the -=
operator.
myDelegate -= Method2;
After this, myDelegate
will no longer call Method2
.
Here is a working example of a multicast delegate.
using System;public delegate void MyDelegate(string message);class Program{static void Main(string[] args){MyDelegate myDelegate = Method1;myDelegate += Method2;myDelegate += Method3;Console.WriteLine("Invoking the multicast delegate:");myDelegate("Hello, World!");// Remove Method2 from the delegatemyDelegate -= Method2;Console.WriteLine("\nAfter removing Method2:");myDelegate("Hello, Again!");}static void Method1(string message){Console.WriteLine("Method1: " + message);}static void Method2(string message){Console.WriteLine("Method2: " + message);}static void Method3(string message){Console.WriteLine("Method3: " + message);}}
When each method associated with a multicast delegate returns a value, it is essential to understand how the values are handled. In C#, a multicast delegate does not automatically aggregate the return values of its methods. Instead, it returns the value of the last method executed. Let’s consider an example below, myDelegate
is a multicast delegate that takes an integer parameter and returns an integer. It is composed of two methods, Method1
and Method2
. When the delegate is invoked with the argument 5
, both methods are executed.
using System;public delegate int MyDelegate(int x);class Program{static void Main(string[] args){MyDelegate myDelegate = Method1;myDelegate += Method2;int result = myDelegate(5);Console.WriteLine("Final Result: " + result);}static int Method1(int x){Console.WriteLine("Method1: " + x);return x * 2;}static int Method2(int x){Console.WriteLine("Method2: " + x);return x + 5;}}
The final result is 10
, which is the return value of the last method (Method2
) executed. If the methods were invoked in a different order, the result would be based on the return value of the last executed method.
Multicast delegates are particularly useful when implementing the observer design pattern or event handling in C# because we can dynamically add and remove event handlers. They are commonly used in GUI frameworks and event-driven programming scenarios where multiple methods must respond to an event or action.
Consider a scenario where a mouse click event triggers a multicast delegate. The delegate, in turn, calls various methods with the mouse click coordinates, enabling different methods to respond uniquely. For instance:
using System;public delegate void MouseClickEventHandler(int x, int y);class ClickHandler{static void Main(string[] args){MouseClickEventHandler clickDelegate = HandleClick1;clickDelegate += HandleClick2;// Simulating a mouse click eventclickDelegate(100, 200);}static void HandleClick1(int x, int y){Console.WriteLine($"Handling click at ({x}, {y}) - Action 1");}static void HandleClick2(int x, int y){Console.WriteLine($"Handling click at ({x}, {y}) - Action 2");}}
In this example, the multicast delegate clickDelegate
triggers two methods (HandleClick1
and HandleClick2
) in response to a mouse click event, each method performs a specific action based on the coordinates.
Free Resources