Multicast Delegates
A multicast delegate holds several methods at once, like a group chat message that reaches everyone. When it is called, they all run one after the other.
In this page:
Syntax
delegate void DelegateName(type parameter);
DelegateName handlers = MethodOne;
handlers += MethodTwo; // add another method
handlers -= MethodOne; // remove one
handlers(argument); // calls all of them
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting the return value of every method in a multicast delegate, when only the last one is returned.
- Using
-=to remove a lambda that is a different instance from the one added. - Forgetting that one method throwing stops the rest.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: