Sobes.tech
Middle

What are group delegates in C#?

sobes.tech AI

Answer from AI

A multicast delegate is an instance of a delegate that contains more than one method in its invocation list.

When a multicast delegate is invoked, all methods in its invocation list are executed sequentially, in the order they were added.

Example of creation and usage:

// Delegate declaration
public delegate void MyDelegate(string message);

// Method 1
public void Method1(string msg)
{
    Console.WriteLine($"Method1 called with: {msg}");
}

// Method 2
public void Method2(string msg)
{
    Console.WriteLine($"Method2 called with: {msg}");
}

// Creating a multicast delegate
MyDelegate myDelegate = Method1;
myDelegate += Method2; // Adding the second method

// Invoking the multicast delegate
myDelegate("Hello, world!");
// Output:
// Method1 called with: Hello, world!
// Method2 called with: Hello, world!

The += operator is used to add a method to the invocation list, and the -= operator to remove it.

Features:

  • If a method in the invocation list throws an exception, execution is interrupted, and other methods may not be called.
  • For delegates that return a value, the multicast delegate returns the value of the last successfully invoked method in the list. The results of previous methods are ignored.