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 in
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
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
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 Func
s 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);