Search⌘ K

Multicasting

Explore the concept of multicasting in C# delegates, where a single delegate instance can call multiple methods in sequence. Learn how to add and remove non-static methods, the behavior of combined delegates, and understand the impact on return values when multiple methods are invoked through one delegate.

We'll cover the following...

Example

Fun part in using delegates is that you can point to multiple functions using them, at the same time. This means that by calling a single delegate, you can actually invoke as many functions as you want.

Let’s look at the example:

C#
using System;
delegate void Procedure();
class DelegateDemo
{
public static void Method1()
{
Console.WriteLine("Method 1");
}
public static void Method2()
{
Console.WriteLine("Method 2");
}
public void Method3()
{
Console.WriteLine("Method 3");
}
static void Main()
{
Procedure someProcs = null;
someProcs += new Procedure(DelegateDemo.Method1);
someProcs += new Procedure(Method2); // Example with omitted class name
DelegateDemo demo = new DelegateDemo();
someProcs += new Procedure(demo.Method3);
someProcs();
}
}

Explanation

The statement someProcs += newProcedure(demo.Method3) adds a non-static method ...