#1,187 – Using a Lambda Expression When Adding to an Invocation List

Recall that an instance of a delegate can refer to more than one method (delegates are multicast).  You can use anonymous methods to declare a new instance of a delegate or to add methods to a delegate’s invocation list.

Since lambda expressions supersede anonymous methods, you can also use lambdas to initialize a delegate or to add to its invocation list.

        private delegate void StringHandlerDelegate(string s);

        static void Main(string[] args)
        {
            // Declare new delegate instance, with lambda
            // as its invocation list
            StringHandlerDelegate del1 = 
                (s) => Console.WriteLine(s);

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

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

            Console.ReadLine();
        }

1187-001

Advertisements

#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");
        }