Thursday, October 18, 2007

C# 2.0 Anonymous Methods

C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.
Here is a simple example of using an anonymous method to find all the even integers from 1...10:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


int[] evenIntegers = Array.FindAll(_integers, delegate(int integer)
{
return (integer%2 == 0);
}
);

The Anonymous Method is:
delegate(int integer)
{
return (integer%2 == 0);
}

which is called for each integer in the array and returns either true or false depending on if the integer is even।


If you don't use an anonymous method, you will need to create a separate method as such:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, IsEven);
private bool IsEven(int integer)
{
return (integer%2 == 0);
}

When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.
Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):
List citiesInFlorida =cities.FindAll(delegate(City city)
{
return city.State.Name.Equals(States.SelectedValue);
}
);

You can also use anonymous methods as such:
button1.Click +=
delegate
{
MessageBox.Show("Hello");
};

which for such a simple operation doesn't “deserve“ a separate method to handle the event.
Other uses of anonymous methods would be for asynchronous callback methods, etc.
Anonymous methods don't have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.