Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does delegate chaining have to start with a null Delegate?

Tags:

c#

delegates

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);
like image 226
MCS Avatar asked Dec 04 '25 21:12

MCS


1 Answers

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)

like image 72
thecoop Avatar answered Dec 07 '25 11:12

thecoop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!