Lambda Expressions to Replace Inline Delegates
(
Oct 07 2007 - 07:40:31 PM by
Timothy Khouri) - [
print blog
post]
With .NET 2.0 came a very handy feature of "inline functions" using a very simple 'delegate + method-body' syntax. I quickly adopted this for those quick "one-liners" that seemed pointless to make an actual method for. Example:
this.CancelButton.Click += delegate
{
this.Response.Redirect("~/View.aspx", true);
};
A function that is basically one line of code, in my opinion, really doesn't need to have a full method created for it. The 'old' way of doing the above would have been something like this:
this.CancelButton.Click += new EventHandler(this.Cancel_Click);
private void Cancel_Click(object sender, EventArgs e)
{
this.Response.Redirect("~/View.aspx", true);
}
Lambda Expressions Replace Inline Delegates
As I pointed out in the title of this blog post, I'm no longer going to be using inline delegates for basically anything. I didn't realize I could do this with lambda expressions until a collegue pointed it out to me, but here is how to accomplish the above using lambda in C#.
this.CancelButton.Click += (sender, args) => this.Response.Redirect("~/View.aspx", true);
It may not look like we've done much, but this is really beautiful! First of all, we are able to utilize the parameters if we wanted to, and secondly we are able to drop the "method body" sytax by removing the { and } characters because this is a one line method.
If you wanted to have multiple lines of code executed, you could do something like this:
this.MyButton.Click += (sender, args)
{
};
Another great benefit of using the lambda expressions in this way is that you can re-use the same variable names because the are "scope specific". Example:
this.MyButton.Click += (sender, args) => DoSomething();
this.MyOtherButton.Click += (sender, args) => DoSomethingElse();
Enjoy!