Delegates Part 5

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Understanding how to compare delegates for equality is important when you try to manipulate

delegate chains, as discussed in the next section.

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);

// Creates a chain represented by the array of delegates


// (NOTE: entry 0 is the head and will be the last delegate called)
public static Delegate Combine(Delegate[] delegateArray);

// Removes a delegate matching values Target/Method from the chain.


// The new head is returned and will be the last delegate called
public static Delegate Remove(Delegate source, Delegate value);
}

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:

Feedback fb1 = new Feedback(FeedbackToConsole);


Feedback fb2 = new Feedback(FeedbackToMsgBox);
Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2);
// The left side of Figure 1 shows what the
// chain looks like after the previous code executes

App appobj = new App();


Feedback fb3 = new Feedback(appobj.FeedbackToStream);
fbChain = (Feedback) Delegate.Combine(fbChain, fb3);
Figure 1 Delegate Chains

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:

Feedback[] fbArray = new Feedback[3];


fbArray[0] = new Feedback(FeedbackToConsole);

Feedback fbChain = Delegate.Combine(fbArray);

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:

You might also like