Search code examples
c#delegatesfunc

How to access previous functions added to a delegate


I'm new to delegates and as far as I understood you can add two functions or even more to a delegate (using +=). But when you activate a delegate it will always call the last function added. What if I wanted to call a function that I added before? let's say I have:

public static int add(int o1, int o2)
{
   return o1 + o2;
}

public static int multiply(int o1, int o2)
{
    return o1 * o2;
}

public static int minus(int o1, int o2)
{
    return o1 - o2;
}

So I use a delegate (actually a Func) to add all those functions.

Func<int, int, int> f;
f = add;
f += multiply;
f += minus;

Now lets say I want to call multiply or add, I cant do this, if I use:

Console.WriteLine(f(1,2));

It will only call minus.

edit

By the way, I'm aware of the possibility to remove function using -=, but if there is a large number of functions, its not convenient. the kind of solutions I'm looking for is indexes (like in arrays) however

f[2](5,3) 

Doesn't seem to work.


Solution

  • This is clearly specified in the language specification (emphasis mine):

    Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. [...] If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

    So it's not that the other delegates are not executed. They are. It's just that only the last delegate's return value is returned. If the other delegates had some side effects, like printing to the console, you would have seen them.

    EDIT

    If you want to access delegates like this:

    f[2](5,3) 
    

    Then you probably need a List<Func<int, int, int>> instead of a multicast delegate.