Sobes.tech
Junior — Middle

Selgitage, mis on multicast-delegaat ja kuidas see töötab .NET delegaatide kontekstis.

sobes.tech AI

Vastus AI-lt

Multicast delegate in .NET is a delegate that can hold references to multiple methods and invoke them sequentially when called.

When you add multiple methods to a delegate (using the += operator), a invocation chain is created. When this delegate is invoked, all methods in the chain are called in order.

Example:

public delegate void Notify(string message);

Notify notifyHandlers = null;

void Handler1(string msg) => Console.WriteLine("Handler1: " + msg);
void Handler2(string msg) => Console.WriteLine("Handler2: " + msg);

notifyHandlers += Handler1;
notifyHandlers += Handler2;

notifyHandlers("Hello");

Output will be:

Handler1: Hello
Handler2: Hello

Thus, multicast delegates are useful for implementing events and callbacks, when you need to notify multiple subscribers.