The code first declares the type AddTolistDelegate. A delegate of this type can hold a reference to a subroutine that takes no parameters.
Next the code defines two methods that match the delegate type.
The form's Load event handler defines two delegate variables A and B, and initializes them so they refer to MethodA and MethodB. It then creates a third delegate C and sets it equal to A + B. It uses the Delegate class's Combine method to add the two delegates and uses DirectCast to convert the result into an AddTolistDelegate object.
The code then executes the delegates. It calls the method referred to by A, then B, and then C. The delegate C contains references to A and B so invoking it makes MethodA and MethodB both execute.
Next the code removed A from C. That removes the call to A's method from the "list" contained in C leaving only B. When the code invokes the result, only MethodB executes.
Note that you can subtract a delegate more than once from another delegate without harm. In this example, the code could remove A from C many times without causing any problems.
However, if you subtract the last delegate from another delegate, then the result is Nothing and you can no longer invoke that result. In this example if the code removed B from C, then C would become Nothing and trying to invoke C would throw an exception.
|