Friday, November 12, 2010

Anonymous Methods

Anonymous Methods

For C# v2.0, there is a new language feature, called anonymous methods, that are similar to delegates, but require less code. 

How Do Anonymous Methods Benefit Me?

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. 

To see the benefit of anonymous methods, you need to look at how they improve your development experience over using delegates. Think about all of the moving pieces there are with using delegates: you declare the delegate, write a method with a signature defined by the delegate interface, delcare the event based on that delegate, and then write code to hook the handler method up to the delegate. 
Because you can hook an anonymous method up to an event directly, a couple of the steps of working with delegates can be removed. 

Implementing an Anonymous Method

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. Listing 21-1 shows how this works.
Listing 21-1. Implementing an Anonymous Method
using System.Windows.Forms;

public partial class Form1 : Form
{
    public Form1()
    {
        Button btnHello = new Button();
        btnHello.Text = "Hello";

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

        Controls.Add(btnHello);
    }
}

The code in Listing 21-1 is a Windows Forms application. It instantiates a Button control and sets its Text to "Hello". Notice the  combine, +=, syntax being used to hook up the anonymous method. You can tell that it is an anonymous method because it uses the delegate keyword, followed by the method body in curly braces. Remember to terminate anonymous methods with a semi-colon.

Essentially, you have defined a method inside of a method, but the body of the anonymous method doesn't execute with the rest of the code. Because you hook it up to the event, the anonymous method doesn't execute until the Click event is raised. When you run the program and click the Hello button, you'll see a message box that say's "Hello" - courtesy of the anonymous method.
Using Controls.Add, adds the new button control to the window. Otherwise the window wouldn't know anything about theButton and you wouldn't see the button when the program runs.

Using Delegate Parameters with Anonymous Methods

Many event handlers need to use the parameters of the delegate they are based on. The previous example didn't use those parameters, so it was more convenient to not declare them, which C# allows. Listing 21-2 shows you how to use parameters if you need to.
Listing 21-2. Using Parameters with Anonymous Methods
using System;
using System.Windows.Forms;

public partial class Form1 : Form
{
    public Form1()
    {
       
        Button btnGoodBye = new Button();
        btnGoodBye.Text = "Goodbye";
       
        btnGoodBye.Click +=
            delegate(object sender, EventArgs e)
            {
                string message = (sender as Button).Text;
                MessageBox.Show(message);
            };

        Controls.Add(btnGoodBye);
    }
}

Beyond implementation details, the real code for you to pay attention to is the implementation of the anonymous method. Notice that the delegate keyword now has a parameter list. this parameter list must match the delegate type of the event that the anonymous method is being hooked up to. The delegate type of the Click event is EventHandler, which has the following signature:

public delegate void EventHandler(object sender, EventArgs e);
Notice the EventHandler parameters. Now, here's how the Button control's Click event is defined:

public event EventHandler Click;
Notice that the delegate type of the Click event is EventHandler. This is why the anonymous method, assigned tobtnGoodBye.Click in Listing 21-2, must have the same parameters as the EventHandler delegate.

Summary

Anonymous methods are a simplified way for you to assign handlers to events. They take less effort than delegates and are closer to the event they are associated with. You have the choice of either declaring the anonymous method with no parameters or you can declare the parameters if you need them.


Note: Article taken from http://www.csharp-station.com All the credits goes to the author written in that website.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.