#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

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

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

  1. Pingback: Dew Drop – September 22, 2014 (#1860) | Morning Dew

  2. Gregory Shields says:

    Cool. Of course, you can also just use Action and not have to declare your own delegate.

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 )

Google+ photo

You are commenting using your Google+ 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: