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;

using System;

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:


1
second:1

The delegates are called in the sequence of adding.

We can subtract delegate method as well.


using System;

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 output:
second:1
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.