Information Technology Reference
In-Depth Information
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—and it's perfectly fine to
think of it that way. You can add a method, or another delegate, to a delegate by 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 15-6 shows the result.
MyDel delVar = Inst.MyM1; // Create and initialize.
delVar += SCl.m3; // Add a method.
delVar += X.Act; // Add a method.
Figure 15-6. Result of adding methods to a delegate
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 plus the
method listed on the right.
Search WWH ::




Custom Search