Professional Documents
Culture Documents
Delegates Part 5
Delegates Part 5
Delegates Part 5
Delegate Chains
By themselves, delegates are incredibly useful. But delegates also support chaining, which makes
them even more useful. In my last column, I mentioned that each MulticastDelegate object has a
private field called _prev. This field holds a reference to another MulticastDelegate object. That is,
every object of type MulticastDelegate (or any type derived from MulticastDelegate) has a reference
to another MulticastDelegate-derived object. This field allows delegate objects to be part of a linked-
list.
The Delegate class defines three static methods that you can use to manipulate a linked-list chain
of delegate objects:
class System.Delegate {
// Combines the chains represented by head & tail, head is returned
// (NOTE: head will be the last delegate called)
public static Delegate Combine(Delegate tail, Delegate head);
When you construct a new delegate object, the object’s _prev field is set to null indicating that
there are no other objects in the linked-list. To combine two delegates into a linked-list, you call one
of Delegate’s static Combine methods:
Figure 1 shows what the chain looks like after all the code executes. You’ll notice that the
Delegate type offers another version of the Combine method that takes an array of Delegate
references. Using this version of Combine, you could rewrite the code shown previously as follows:
When a delegate is invoked, the compiler generates a call to the delegate type’s Invoke method (as I
discussed in the previous column). To refresh your memory, the example in that column declared a
Feedback delegate as the following code does: