Skip to content

Adding Methods to Delegates

Although you saw in the previous section that delegates are, in reality, immutable, C# provides syntax for making it appear that you can add a method to a delegate, using the += operator. For example, the following code “adds” two methods to the invocation list of the delegate. The methods are added to the bottom of the invocation list. Figure 14-7 shows the result. making it appear that you can add a method to a delegate, using the += operator.

For example, the following code “adds” two methods to the invocation list of the delegate. The methods are added to the bottom of the invocation list. Below figure shows the result.

Result of “adding” methods to a delegate. In reality, because delegates are immutable, the resulting delegate with three methods in its invocation list is an entirely new delegate pointed at by the variable.

What is actually happening, of course, is that when the += operator is used, a new delegate is created, with an invocation list that is the combination of the delegate on the left and the method listed on the right.

This new delegate is then assigned to the delVar variable. You can add a method to a delegate more than once. Each time you add it, it creates a new element in the invocation list.

Leave a Reply

Your email address will not be published.