A multicast delegate is a delegate that can invoke multiple methods, so long as the methods all have the same signature as the delegate's definition. Multicast delegates are the steppingstone between standard delegates and the use of events. When you understand both delegates and multicast delegates, you will be ready to start working with events.
You create a multicast delegate through composition. Composing multiple delegates is accomplished with the +, -, +=, and -= operators. To make a delegate invoke multiple methods, you simply add the method to an existing delegate using + or +=. To remove a method from a multicast delegate, you use the or the -= overloaded operators.
The code in Listing 9.3 provides an illustration of how to create and invoke multicast delegates. In addition, the sample also shows creating a multicast delegate from both named and anonymous methods, and how to iterate through the list of methods that will be invoked by a multicast delegate.
Listing 9.3. Multicast Delegate Sample
When you run the preceding code, the output looks as follows, illustrating how a single invocation to a multicast delegate can invoke the target of that delegate multiple times:
Hello World [8:50 PM] Hello World Multicasted! Multicasted! [8:50 PM] Multicasted! [8:50 PM] Hello World (again) Really multicasted Really multicasted [8:50 PM] Really multicasted [8:50 PM] Really multicasted [8:50 PM] Hello! [Anonymous] Hello! Methods in the mpd3 multicast: PrintStampedMessage <Main>b__0
As you can see, multicast delegates are an extremely powerful feature with virtually unlimited applications. Events, which are one of those applications, are discussed next. It is also worth noting that in the preceding output, the anonymous method has been assigned a name by the CLR: <Main>b__0. All methods must be identified by a name, even anonymous methods, so the CLR generates a name dynamically based on the scope and sequence of the method.