Multicast delegate

In this chapter you will learn:

  1. How to use multicast delegate
  2. Example to create multicast delegate
  3. Subtract delegate
  4. Use new operator to create delegate

Use multicast delegate

C# overloads the + and - operators for delegate. By using + and - we can add methods to or subtract methods from a delegate type variable.

delegateVariable += aMethod;

can be rewritten as

delegateVariable = delegateVariable + aMethod;

Example to create multicast delegate

using System;/*from   ja va2s  .  c  o  m*/

delegate void Printer(int i);
class Test
{
    static void consolePrinter(int i)
    {
        Console.WriteLine(i);
    }

    static void consolePrinter2(int i)
    {
        Console.WriteLine("second:" + i);
    }

    static void Main()
    {
        Printer p = consolePrinter;
        p += consolePrinter2;

        p(1);

    }
}

The output:

The delegates are called in the sequence of adding.

Subtract delegate

We can subtract delegate method as well.

using System;/* j a v a 2s .  com*/

delegate void Printer(int i);
class Test
{

    static void consolePrinter(int i)
    {
        Console.WriteLine(i);
    }

    static void consolePrinter2(int i)
    {
        Console.WriteLine("second:" + i);
    }

    static void Main()
    {
        Printer p = consolePrinter;
        p += consolePrinter2;
        p -= consolePrinter;
        p(1);

    }
}

The code above generates the following result.

Use new operator to create delegate

using System;/*from j a  va  2s .  co  m*/

class MainClass
{
  delegate int MyDelegate(string s);
  static void Main(string[] args)
  {
    string MyString = "Hello World";

    
    MyDelegate Multicast = null;

    Multicast += new MyDelegate(DoSomething);
    Multicast += new MyDelegate(DoSomething2);

    Multicast(MyString);
  }

  static int DoSomething(string s)
  {
    Console.WriteLine("DoSomething");
    
    return 0;
  }
  static int DoSomething2(string s)
  {
      Console.WriteLine("DoSomething2");
    return 0;
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Casting delegate variables
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables