1

I am trying to add 2 more functions to my delegate but it seems it doesn't process the functions I added. Following program outputs 5. I expect 10. Why is this the case?

using System;

namespace abc
{
public delegate int Del(int k);

class Class1
{
    public int Add2(int value)
    {
        return value = value + 2;
    }

    public int Add3(int value)
    {
        return value = value + 3;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Class1 c = new Class1();
        Del mydel = c.Add2;
        mydel += c.Add3;
        mydel += c.Add2;

        Console.WriteLine(mydel(3));
        Console.ReadLine();
    }
}
}
Lyrk
  • 1,936
  • 4
  • 26
  • 48
  • `mydel(3)` doesn't actually change the value of the argument, so you get the result of the last function which is `Add2(3)` which is 3+2 so 5 – Rafalon Apr 24 '17 at 14:13

1 Answers1

5

What happens when you call mydel(3) is this:

  1. Add2(3) is called. This returns 3 + 2 = 5, the return value of which is discarded.
  2. Add3(3) is called. This returns 3 + 3 = 6, the return value of which is discarded.
  3. Add2(3) is called. This returns 3 + 2 = 5, the return value of which is printed.

When you chain delegates, the return value of one is NOT passed as a parameter to a chained one.

Note that the delegates are called in LIFO order.

If you want to see how to actually chain functions together using delegates, see this thread.

Alternatively, as per the linked answer (and as mentioned by Toskr in the comments below), you can use GetInvocationList() and DynamicInvoke() to chain the methods together, but this is a very unusual thing to do:

static void Main()
{
    Class1 c = new Class1();
    Del mydel = c.Add2;
    mydel += c.Add3;
    mydel += c.Add2;

    int result = 3;

    foreach (var func in mydel.GetInvocationList())
    {
        result = (int)func.DynamicInvoke(result);
    }

    Console.WriteLine(result);
}
Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276