7.2. Obtaining Return Values from Each Delegate in a Multicast Delegate

Problem

You have added multiple delegates to a single multicast delegate. Each of these individual delegates returns a value that is required by your application. Ordinarily, the values returned by individual delegates in a multicast delegate are lost; all except the value from the last delegate to fire, whose return value is returned to the calling application. You need to be able to access the return value of each delegate that is fired in the multicast delegate.

Solution

Use the GetInvocationList method as in Recipe 7.1. This method returns each individual delegate from a multicast delegate. In doing so, we can invoke each delegate individually and get its return value. The following method creates a multicast delegate called All and then uses GetInvocationList to fire each delegate individually. After firing each delegate, the return value is captured:

public void TestIndividualInvokesRetVal( )
{
    MultiInvoke MI1 = new MultiInvoke(TestInvoke.Method1);
    MultiInvoke MI2 = new MultiInvoke(TestInvoke.Method2);
    MultiInvoke MI3 = new MultiInvoke(TestInvoke.Method3);

    MultiInvoke All = MI1 + MI2 + MI3;

    int retVal = -1;

    Console.WriteLine("Invoke individually (Obtain each return value):");
    foreach (MultiInvoke individualMI in All.GetInvocationList( ))
    {
        retVal = individualMI( );
        Console.WriteLine("\tOutput: " + retVal);
    }
}

The following delegate defines the MultiInvoke delegate:

public delegate int MultiInvoke( );

The ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.