#1,168 – Using a Lambda Expression as an Event Handler

You can use a lambda expression wherever a delegate instance is expected.  This includes using a lambda expression when defining an event handler.

        static void Main(string[] args)
        {
            Dog d = new Dog("Bowser");

            // Method #1 - Subscribe to Barked event using named method
            d.Barked += d_Barked;

            // Method #2 - Subscribe to Barked event using lambda expression
            d.Barked += (s, e) => { Console.WriteLine("My dog says {0}", e); };

            d.Bark();

            Console.ReadLine();
        }

        static void d_Barked(object sender, string e)
        {
            Console.WriteLine("Dog {0} just barked, saying {1}",
                ((Dog)sender).Name, e);
        }

1168-001

Advertisements

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

2 Responses to #1,168 – Using a Lambda Expression as an Event Handler

  1. Xavier Fischer says:

    Is there are way to unsubscribe to the event using the lambda syntax used.
    By the way, thanks for this blog, it is a great resource !

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 )

w

Connecting to %s

%d bloggers like this: