0
0
C Sharp (C#)programming~5 mins

Multicast delegates in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Multicast delegates let you call multiple methods with one delegate. It helps when you want to do many things in order with a single call.
You want to notify several parts of your program about an event.
You want to run multiple methods one after another without calling each separately.
You want to add or remove methods dynamically to a list of actions.
You want to keep your code organized by grouping related method calls.
You want to implement event handling where many listeners respond to one event.
Syntax
C Sharp (C#)
delegate void MyDelegate();

MyDelegate d = Method1;
d += Method2;
d();
Use '+=' to add methods to the delegate list.
Use '-=' to remove methods from the delegate list.
Examples
Calls Alert and then Log methods in order.
C Sharp (C#)
delegate void Notify();

void Alert() { Console.WriteLine("Alert!"); }
void Log() { Console.WriteLine("Log entry"); }

Notify notify = Alert;
notify += Log;
notify();
Calls Hello and Bye with the same message.
C Sharp (C#)
delegate void ShowMessage(string msg);

void Hello(string msg) { Console.WriteLine($"Hello {msg}"); }
void Bye(string msg) { Console.WriteLine($"Bye {msg}"); }

ShowMessage show = Hello;
show += Bye;
show("Friend");
Sample Program
This program creates a multicast delegate that calls two methods. Then it removes one and calls the remaining method.
C Sharp (C#)
using System;

class Program
{
    delegate void MultiDelegate();

    static void First() { Console.WriteLine("First method called"); }
    static void Second() { Console.WriteLine("Second method called"); }

    static void Main()
    {
        MultiDelegate multi = First;
        multi += Second;

        multi();

        multi -= First;

        Console.WriteLine("After removing First method:");
        multi();
    }
}
OutputSuccess
Important Notes
If any method in the multicast delegate throws an exception, the remaining methods will not be called.
The return value of a multicast delegate is the return value of the last method called.
Multicast delegates work only with void return types or when you don't need the return value.
Summary
Multicast delegates let you call multiple methods with one delegate call.
Use '+=' to add and '-=' to remove methods from the delegate list.
They are useful for event handling and running multiple actions in order.