Delegate Chains

I had previously written that a delegate is a class containing a reference to a method. A delegate can actually contain a reference to multiple methods ( which can be in different classes ). When a delegate contains multiple targets, this is called a delegate chain. Typically you would only chain when the return type on the delegate is void.

How do I create a delegate chain ?

You do this by adding the target method to the invocation list of the delegate using += ( compiler syntactic sugar ). In the example below, I’m going to add 3 methods to my delegate:

ChainSimple1

Can I invoke the same delegate more than once in my chain ?

Yes, simply add it again using the += construct. In the example below, I add the method Foo twice.

ChainMulti

How do I remove a delegate item from my chain ?

Use the -= construct to remove a delegate from the chain. Removal operates on a LIFO basis ( last in first out )

unchain

What do += and -= actually do ?

Each delegate object holds a collection of the target/methods it is supposed to call. This is called the “invocation list”. With +=, you are adding to the collection. With -= you are removing from the collection

+= calls the Combine method of the static delegate class. As delegates are immutable, the call to the static Combine method creates a new delegate chain and the reference is refreshed to point to this new object heap

combine1

-= calls the Remove method of the static delegate class. As delegates are immutable, the call to the static Remove method creates a new delegate chain and the reference is refreshed to point to this new object heap

minusequalsExplained

 

 

Posted in Uncategorized

Leave a comment

Design a site like this with WordPress.com
Get started