Section 17.2. Multicasting


17.2. Multicasting

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.



Learning C# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net