#1,020 – Removing Methods from a Delegate’s Invocation List

You can use the += syntax to add methods to a delegate’s invocation list and then -= syntax to remove methods from its invocation list.  In either case, you add or remove methods that are included in a second delegate’s invocation list from the first delegate’s invocation list.

In the example below, we remove del2’s invocation list (Method2, Method3) from del1’s invocation list (Method1, Method2, Method3, Method4, Method5).  del1’s invocation list then becomes: Method1, Method4, Method5.

            // del1 invokes 5 methods
            StringHandlerDelegate del1 = Method1;
            del1 += Method2;
            del1 += Method3;
            del1 += Method4;
            del1 += Method5;
            del1("del1 Howdy");
            Console.WriteLine();

            // del2 invokes 2 methods
            StringHandlerDelegate del2 = Method2;
            del2 += Method3;
            del2("del2 Howdy");
            Console.WriteLine();

            // Remove del2's methos from del1's invocation list
            del1 -= del2;
            del1("del1 Howdy again");

1020-001
When removing more than one method, the invocation list to be removed must be a contiguous subset of the larger invocation list.  (E.g. {Method2, Method3} rather than {Method2, Method4}).

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,020 – Removing Methods from a Delegate’s Invocation List

  1. Pingback: Dew Drop – January 28, 2014 (#1711) | Morning Dew

Leave a comment