Retrieving Values from Multicast Delegates

In most situations, the methods you’ll encapsulate with a multicast delegate will return void. In fact, the most common use of multicast delegates is with events, and you will remember that by convention, all events are implemented by delegates that encapsulate methods that return void (and also take two parameters: the sender and an EventArgs object).

It is possible, however, to create multicast delegates for methods that do not return void. In the next example, you will create a very simple test class with a delegate that encapsulates any method that takes no parameters but returns an integer.

public class ClassWithDelegate
{
  public delegate int DelegateThatReturnsInt( );
  public DelegateThatReturnsInt theDelegate;

To test this, you’ll implement two classes that subscribe to your delegate. The first encapsulates a method that increments a counter and returns that value as an integer:

public class FirstSubscriber
{
  private int myCounter = 0;

  public void Subscribe(ClassWithDelegate theClassWithDelegate)
  {
    theClassWithDelegate.theDelegate += 
      new ClassWithDelegate.DelegateThatReturnsInt(DisplayCounter);
  }

  public int DisplayCounter( )
  {
    return ++myCounter;
  }
}

The second class also maintains a counter, but its delegated method doubles the counter and returns that doubled value:

public class SecondSubscriber { private int myCounter = 0; public void Subscribe(ClassWithDelegate theClassWithDelegate) { theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturnsInt(Doubler); ...

Get Programming C#, Third Edition 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.