Multicast Delegates
In this page:
Multicast Delegates
A delegate can reference more than one method at once by combining them with +=, forming a multicast delegate. Invoking it calls every attached method in order. -= removes a method from the invocation list. This is exactly the mechanism events use under the hood.
Note: If a multicast delegate has a non-void return type, invoking it only gives you the last method's return value.
Example: Multicast Delegates
using System;
delegate void Notify(string message);
class Program
{
static void LogToConsole(string msg) => Console.WriteLine("Console: " + msg);
static void LogWithPrefix(string msg) => Console.WriteLine("[LOG] " + msg);
static void Main(string[] args)
{
Notify notify = LogToConsole;
notify += LogWithPrefix;
notify("System started");
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: