Anonymous methods is a great new feature in C# 2.0 which also is a very important step for the next version of C#. When I first read about anonymous methods, I couldn't really see when and why I would use them, but now I use them frequently. So what is so great about anonymous methods?
In this short exploration of anonymous methods, I would like to point out two things that is the most common reason for me too use them, and I will do it with an example:
private delegate string GetUserNameByEmailAsync();
public override string GetUserNameByEmail(string email)
{
IAsyncResult adRes;
string adUserName;
//Anonymous method
GetUserNameByEmailAsync ad = delegate()
{
//Anonymous method accessing local variable email
return this.ActiveDirectoryMembershipProvider.GetUserNameByEmail(email);
};
adRes = ad.BeginInvoke(null, null);
IAsyncResult sqlRes;
string sqlUserName;
//Anonymous method
GetUserNameByEmailAsync sql = delegate()
{
return this.SqlMembershipProvider.GetUserNameByEmail(email);
};
sqlRes = sql.BeginInvoke(null, null);
WaitHandle.WaitAll(new WaitHandle[] {adRes.AsyncWaitHandle, sqlRes.AsyncWaitHandle});
adUserName = ad.EndInvoke(adRes);
sqlUserName = ad.EndInvoke(sqlRes);
if (!string.IsNullOrEmpty(adUserName))
return adUserName;
else
return sqlUserName;
}
In this small example I want to make two asynchronous calls and then wait for the result. For both async calls and anonymous methods I need a delegate GetUserNameByEmailAsync. In VB or C# 1, I would have had to create two methods in my class to be able to use this async pattern, but now in C# 2 it is easy to have an anonymous method with the rest of my code. It's methods that would never be called from anywhere else and this is my first common need. A second thing that is so great with anonymous methods is that they can access my local variables. Notice that the delegate declarations does not have any arguments, but still I'm using a variable called email in the method, and this is possible because anonymous methods have access to all variables that are accessible in the rest of my main method. This is really useful which you soon will discover if you start using anonymous methods.