Monday, 20 August 2018

C#: Multi cast delegate continuation

This is continuation to my previous post. In my previous post, I explained about multi cast delegates using void methods. What if your multi-cast delegate points to non-void methods.

As per the documentation, if the delegate is multi-cast delegate and point to non-void methods, then the value returned by the last invoked method is returned.

Program.cs
using System;

class Program
{
    public delegate int Process(int num);

    public static int square(int num)
    {
        return num * num;
    }

    public static int cube(int num)
    {
        return num * num * num;
    }

    public static int twice(int num)
    {
        return 2 * num;
    }
   
    static void Main(string[] args)
    {
        Process myDelegate = new Process(square);
        myDelegate += cube;
        myDelegate += twice;

        int result = myDelegate(10);

        Console.WriteLine("result : {0}", result);  
    }
}

Output
result : 20


Notify following snippet. Since the method ‘twice’ is the last method to be called in delegate chain, result is assigned with 20.

        Process myDelegate = new Process(square);
        myDelegate += cube;
        myDelegate += twice;

        int result = myDelegate(10);

If the delegate has out parameter, then the value of the out parameter is assigned to the return value of the invoked method.

Program.cs
using System;

class Program
{
    public delegate void Process(out int num);

    public static void method1(out int num)
    {
        num = 10;
    }

    public static void method2(out int num)
    {
        num = 101;
    }

    static void Main(string[] args)
    {
        Process myDelegate = new Process(method1);
        myDelegate += method2;

        int result = -1;

        Console.WriteLine("result before calling delegate : {0}", result);

        myDelegate(out result);

        Console.WriteLine("result after calling delegate : {0}", result);
    }
}

Output
result before calling delegate : -1
result after calling delegate : 101




Previous                                                 Next                                                 Home

No comments:

Post a Comment