12

I am trying to understand concept of delegates and have got a query. Suppose that we have a delegate defined with return type as int and accepting in 2 parameters of type int.

Delegate declaration:

 public delegate int BinaryOp(int x, int y); 

Now, lets say we have 2 methods (add and multiply) both accepting 2 int parameters and returning an int result.

Code:

    static int Add(int x, int y)  
   {     
        return x + y; 
    }  

    static int Multiply(int x, int y)  
   {     
        return x * y; 
    }  

Now, when add and multiply methods are added into this delegate, and then when the delegate is called like:

BinaryOp b = new BinaryOp(Add);
b+=new BinaryOp(Multiply);

int value=delegate_name(2,3);

Then, as per my understanding, both the methods are called. Now, result from which of the 2 methods is stored in the value variable? Or does it return an array in such case?

helloworld
  • 894
  • 1
  • 8
  • 18

3 Answers3

11

Actually, with a little bit of trickery and casting, you can get all of the results like this:

var b = new BinaryOp(Add);
b += new BinaryOp(Multiply);

var results = b.GetInvocationList().Select(x => (int)x.DynamicInvoke(2, 3));
foreach (var result in results)
    Console.WriteLine(result);

With output:

5
6
Alex
  • 13,024
  • 33
  • 62
7

You will get the return value of the last method added to the multicast delegate. In this case, you will get the return value of Multiply.

See the documentation for more on this: https://msdn.microsoft.com/en-us/library/ms173172.aspx

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
2

Yes, invoking a multicast delegate calls all subscribed methods, but no, an array of results is not returned - only the result returned by the last subscriber is returned.

To obtain the returned results of all subscribers, what you could do instead is to build a collection of typed Funcs which you can then invoke and collate the results:

 IEnumerable<int> InvokeResults(IEnumerable<Func<int, int, int>> operations, 
                                int x, int y)
 {
     return operations.Select(op => op(x, y));
 }

And invoke like such:

 var results = InvokeResults(new Func<int, int, int>[] {Add, Multiply}, 2, 3);
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285