Skip to content

Multicast delegates

Context: Delegates can hold multiple methods using the + and - operators. Invoking a multicast delegate calls all methods in order.

public delegate void Notify(string message);
public static void LogToFile(string msg) => Console.WriteLine($"File: {msg}");
public static void LogToConsole(string msg) => Console.WriteLine($"Console: {msg}");
Notify logger = LogToFile;
logger += LogToConsole; // add second method
logger("Hello"); // both methods are called
logger -= LogToFile; // removes first method
logger("Only console");

For multicast delegates with non‑void return, only the last method’s return value is kept. Use GetInvocationList() to process all.

foreach (Notify n in logger.GetInvocationList())
{
n("Processing");
}

Event notifications: Multiple subscribers to an event are stored as a multicast delegate. Raising the event notifies all subscribers.

Example: In ASP.NET Core, the IApplicationLifetime events use multicast delegates.