tags:

views:

92

answers:

2

In CLR via C#, Jeffrey Richter gives the following example of delegate chaining (pg. 406):

internal delegate void Feedback(Int 32 value);

Feedback fb1 = new Feedback(method1);  // in the book, these methods
Feedback fb2 = new Feedback(method2);  // have different names
Feedback fb3 = new Feedback(method3); 

Feedback fbChain = null;
fbChain = (Feedback) Delegate.Combine(fbChain, fb1);
fbChain = (Feedback) Delegate.Combine(fbChain, fb2);
fbChain = (Feedback) Delegate.Combine(fbChain, fb3);

Why does the first call to Delegate.Combine have to pass in a null Delegate? Here's how I would have thought it should be written:

Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2);
fbChain = (Feedback) Delegate.Combine(fbchain, fb3);
+2  A: 

Well, according to the definition it seems you can reduce it even further:

Feedback fbChain = (Feedback) Delegate.Combine(fb1, fb2, fb3);
ANeves
+5  A: 

Correct - you don't have to start with a null. What Delegate.Combine does is return a new delegate with the invocation list of the first argument appended with the invocation list of the second argument. If one of the arguments is null it just returns the other delegate you passed in.

Also, you don't have to use Combine directly. You can do this:

Feedback fbChain = method1;
fbChain += method2;
fbChain += method3;

or

fbChain = new Feedback(method1) + new Feedback(method2) + new Feedback(method3);

as + for delegates maps onto Combine. This is also typechecked by the compiler, rather than having to use Delegate.Combine (which will only fail at runtime if the signatures don't match)

thecoop
+1 - good, accurate and thorough answer
ANeves