#551 – Use Anonymous Method When Adding to an Invocation List

Recall that an instance of a delegate can refer to more than one method (delegates are multicast).  In addition to using an anonymous method to declare a new instance of a delegate, you can also use anonymous methods when adding a new method to an existing delegate instance.  (Adding to the delegate instance’s invocation list).

        private delegate void StringHandlerDelegate(string s);

        static void Main()
            // Declare new delegate instance, with anonymous
            // method in its invocation list
            StringHandlerDelegate del1 =
                delegate (string s) { Console.WriteLine(s); };

            // Now add a 2nd method to delegate, also using
            // anonymous method
            del1 +=
                delegate(string s) { Console.WriteLine(new string(s.Reverse().ToArray())); };

            // When we invoke the delegate, both methods are
            // called
            del1("Mairzy Doats and Dozy Doats");


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

2 Responses to #551 – Use Anonymous Method When Adding to an Invocation List

  1. vanko says:

    when I should write ‘public delegate …’ and when I should write ‘private delegate …’ I mean what is the difference between ‘public delegate …’ and ‘private delegate …’ ???

    • Sean says:

      You would make a delegate public when you want the delegate type accessible to code outside of the class in which its defined. For example, if the delegate type will be used as the declared type of a public event, then it must be public in order for client code to subscribe to that event.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: