At times, it is desirable to call two (or more) implementing methods through a single delegate. This becomes particularly important when handling events (discussed later in this chapter).
The goal is to have a single delegate that invokes more than one method. For example, when a button is pressed, you might want to take more than one action. This process of calling more than one method with a single delegate is called multicasting .
Two delegates can be combined with the addition operator (+
). The result is a new multicast delegate
that invokes both of the original implementing methods. For example,
assuming Writer
and Logger
are delegates, the following line will
combine them and produce a new multicast delegate named myMulticastDelegate
:
myMulticastDelegate = Writer + Logger;
You can add delegates to a multicast delegate using the
plus-equals (+=
) operator. This
operator adds the delegate on the right side of the operator to the
multicast delegate on the left. For example, assuming Transmitter
and myMulticastDelegate
are delegates, the
following line adds Transmitter
to
myMulticastDelegate
:
myMulticastDelegate += Transmitter;
The power of multicast delegates is best understood in terms of events, discussed in the next section. When an event such as a button press occurs, an associated multicast delegate can invoke a series of event handler methods that will respond to the event.