Friday, January 11, 2013

Anonymous Methods.

An anonymous method is a method without a name - which is why it is called anonymous. You don't declare anonymous methods like regular methods. Instead they get hooked up directly to events.

>> Because you can hook an anonymous method up to an event directly, a couple of the steps of working with delegates can be removed.

>> An anonymous method uses the keyword, delegate, instead of a method name. This is followed by the body of the method. Typical usage of an anonymous method is to assign it to an event.

By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

Example:

       Button btnHello = new Button();
        btnHello.Text = "Hello";

        btnHello.Click +=
            delegate
            {
                MessageBox.Show("Hello");
            };

        Controls.Add(btnHello);


Using Parameters with Anonymous Methods:

        Button btnHello = new Button();
        btnHello.Text = "Hello";

        btnHello.Click +=
            delegate
            {
                MessageBox.Show("Hello");
            };

        Button btnGoodBye = new Button();
        btnGoodBye.Text = "Goodbye";
        btnGoodBye.Left = btnHello.Width + 5;
        btnGoodBye.Click +=
            delegate(object sender, EventArgs e)
            {
                string message = (sender as Button).Text;
                MessageBox.Show(message);
            };

        Controls.Add(btnHello);
        Controls.Add(btnGoodBye);




No comments:

Post a Comment