A delegate in C# is a type that defines a reference to a method. A multicast delegate is a delegate that can refer to and invoke multiple methods. When a multicast delegate is invoked, it invokes all of the methods it references in the order in which they were added to the delegate.
Here is an example of using a multicast delegate in C#:
Here is an example of using a multicast delegate in C#:
delegate void MyDelegate(string message);
class Program
{
static void Main(string[] args)
{
MyDelegate delegate1 = new MyDelegate(Method1);
MyDelegate delegate2 = new MyDelegate(Method2);
MyDelegate delegate3 = new MyDelegate(Method3);
MyDelegate multicastDelegate = delegate1 + delegate2 + delegate3;
multicastDelegate("Hello from the multicast delegate");
}
static void Method1(string message)
{
Console.WriteLine("Method 1: " + message);
}
static void Method2(string message)
{
Console.WriteLine("Method 2: " + message);
}
static void Method3(string message)
{
Console.WriteLine("Method 3: " + message);
}
}
Output:
Method 1: Hello from the multicast delegate
Method 2: Hello from the multicast delegate
Method 3: Hello from the multicast delegate
In this example, `MyDelegate` is a delegate type that refers to methods that take a string parameter and return `void`. The `delegate1`, `delegate2`, and `delegate3` variables each reference a different method. The `multicastDelegate` variable is created by adding the three delegate instances together using the `+` operator. When `multicastDelegate` is invoked, it invokes all three methods it references.
Comments
Post a Comment