Combine Delegates Multicast Delegates

suggest change

Addition \+ and subtraction \- operations can be used to combine delegate instances. The delegate contains a list of the assigned delegates.

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace DelegatesExample {
    class MainClass {
        private delegate void MyDelegate(int a);

        private static void PrintInt(int a) {
            Console.WriteLine(a);
        }

        private static void PrintType<T>(T a) {
            Console.WriteLine(a.GetType());
        }

        public static void Main (string[] args)
        {
            MyDelegate d1 = PrintInt;
            MyDelegate d2 = PrintType;

            // Output:
            // 1
            d1(1);

            // Output:
            // System.Int32
            d2(1);

            MyDelegate d3 = d1 + d2;
            // Output:
            // 1
            // System.Int32
            d3(1);

            MyDelegate d4 = d3 - d2;
            // Output:
            // 1
            d4(1);

            // Output:
            // True
            Console.WriteLine(d1 == d4);
        }
    }
}

In this example d3 is a combination of d1 and d2 delegates, so when called the program outputs both 1 and System.Int32 strings.

Combining delegates with non void return types:

If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked. The preceding methods are still called, but their return values are discarded.

class Program
{
    public delegate int Transformer(int x);

    static void Main(string[] args)
    {
        Transformer t = Square;
        t += Cube;
        Console.WriteLine(t(2));  // O/P 8 
    }

    static int Square(int x) { return x * x; }

    static int Cube(int x) { return x*x*x; }
}

t(2) will call first Square and then Cube. The return value of Square is discarded and return value of the last method i.e. Cube is retained.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Delegates:
* Combine Delegates Multicast Delegates

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
94 Delegates
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script