Calling a delegate with multiple functions that have return values
I am trying to understand the concept of delegates and get a request. Suppose we have a delegate defined with a return type of int and taking 2 int parameters.
Delegate declaration:
public delegate int BinaryOp(int x, int y);
Now let's say we have 2 methods (addition and multiplication) that take 2 int parameters and return 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 to 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 methods are called. Now the result from which of the 2 methods is stored in the value variable? Or does it return an array in such a case?
source to share
Actually, with a little bit of cheating and casting, you can get all 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 the exit:
5 6
source to share
You will get the return value of the last method added to the multicast delegate. In this case, you will get the return value Multiply
.
See documentation for details: https://msdn.microsoft.com/en-us/library/ms173172.aspx
source to share
Yes, calling the multicast delegate invokes all subscribed methods, but no, no result array is returned β the result returned by the last subscriber is returned .
To get the returned results for all subscribers, you can instead create a typed set Func
, which you can then call and match the results:
IEnumerable<int> InvokeResults(IEnumerable<Func<int, int, int>> operations,
int x, int y)
{
return operations.Select(op => op(x, y));
}
And it is called like this:
var results = InvokeResults(new Func<int, int, int>[] {Add, Multiply}, 2, 3);
source to share