A useful feature of delegates is that delegates can point to more than one method. A delegate that points to multiple methods is called Multicast Delegate. When invoking Multicast Delegate all methods that he points to are invoked.  We add methods to delegate by using + or += operator. Methods can be removed from delegate by using – or -= operators.

When delegate has return type void, all methods are executed. The same is with all other return types. Difference is that when return type is not void, we will receive only value of last method executed.

 

Examples of Multicast Delegate using void return type:

 

Add methods to delegate by using + operator

We will create console application that will print content of four methods by using delegates.

First we created our new delegate VoidDelegate that has return type void and takes no input parameters. Then, inside our Main method, we defined 5 VoidDelegates, and instantiate four of the them. After we are done with instantiating 4 delegates, we assign those 4 delegates using + operator to fifth delegate. Lastly, we invoke the delegate. Console output will show all 4 ShowMessage methods results.

Remove methods from delegate by using – operator

Let’s rework our previous code so we can see example of removing methods from a delegates by using – operator. Next example will show you only Main method, because no changes are needed to be maid for ShowMessage methods.

First part of a code is same as in previous example, but later on we just use – operator to unsubscribe voidDelegate1  delegate (that uses ShowMessageOne method) from voidDelegate5 delegate. Note that ShowMessageOne  message is not shown.

 

Add methods to delegate by using += operator

Seems that += operators shortened our code and made it a lot readable. This time we needed to declare only one delegate and add methods to him by only using += operators.

Remove methods from delegate by using -= operator

 

Example of Multicast Delegate using string return type

While running this app, try entering debug mode, you will see that all methods were hit but only ShowMessageFour message was sent. Remember that while consuming your delegates.

 

We will continue delegates discussion with Anonymous methods.