Anonymous Methods in C# 2.0

I love the anonymous methods feature that was added to C# 2.0. I got a taste of this feature in college when I used Java (which refers to them as anonymous inner classes). Regardless, this is yet another feature to help developers write cleaner code.

For example, let’s say your application has a button that, upon clicking, shows an “About” dialog, which displays various information about your application (e.g. version, logo, etc.). Upon closing that dialog, you’d like to display a message box, telling your user that they just saw your “About” dialog box (because users like having to click a lot…).

In C# 1.x, you’d have to write the following code to accomplish this:

private void Button1_Click(object sender, EventArgs e)
{
    AboutDialog dlg = new AboutDialog();
    dlg.Closed += new EventHandler(OnAboutDlgClosed);
    dlg.ShowDialog(this);
}

// separate method for handling the form close event.
private void OnAboutDlgClosed(object sender, EventArgs e)
{
    MessageBox.Show("You just saw my About dialog!");
}

However, in C# 2.0, you can do the same thing using anonymous methods:

private void Button1_Click(object sender, EventArgs e)
{
    AboutDialog dlg = new AboutDialog();
    // .NET 2.0 changed the name of the event to FormClosed
    dlg.FormClosed += delegate
    {
        MessageBox.Show("You just saw my About dialog!");
    }
    dlg.ShowDialog(this);
}

That’s it. Frickin’ sweet!

Ok, so there are a couple drawbacks that I’ve found while using anonymous methods. First, I’ve found that I cannot use the “Edit and Continue” feature in the Visual Studio 2005 Debugger. That is, I am not allowed to make a change in the method or anonymous method while stepping through the code — instead, I have to make my code change and restart the debugger. A minor nuisance, but still a nuisance.

The other potential issue is that, assuming the code in the anonymous method needs to be executed in response to multiple events, some developers may find themselves copying and pasting the code in several places of their application, thus ignoring the general rule of code re-use.

This second issue can be very subtle. It is a problem of design, and it is up to the developer to be on the lookout for it. In cases like this, the C# 1.x example would be a good solution that promotes code re-use.

Leave a Reply

Your email address will not be published. Required fields are marked *