I was playing around with delegates and anonymous methods and came across the code below:
delegate int IntegerGenerator();
static void Main()
{
IntegerGenerator numberGenerator;
numberGenerator = () =>
{
Console.WriteLine("returns 7");
return 7;
};
numberGenerator += () =>
{
Console.WriteLine("returns 3");
return 3;
};
// This will always return 3
var num = numberGenerator();
Console.WriteLine("Return value: {0}", num);
}
I am interested by the returning values from all methods in the Invocation list of the delegate. However it seems as the only value that is given back is from the last method to be attached to the delegate. A possible workaround is by inputting a collection and just adding the result to it. However that doesn't seem to be the right way to approach this because of the return type of the delegate.
How can I capture all return values from the attached methods in the delegate?
You'd need to use MulticastDelegate.GetInvocationList
and invoke each delegate separately. For example:
List<int> results = numberGenerator.GetInvocationList()
.Cast<IntegerGenerator>()
.Select(x => x())
.ToList();
See more on this question at Stackoverflow