Gary Devenay

Web Development

Basic Lambda Expressions Using ASP.NET 3.5 and C#

July31

One of many new features introduced into the .NET 3.5 framework are Lambda Expressions.

Lambda Expressions are a method of programmatically assigning Event Handlers to Events. There are a few ways that this can be acheived though Lambda Expressions prove to be the quickest, cleanest and most effective way of doing so.

Lambda Expressions are similar to anonymous methods only taken one step further. For instance if you had a button on your page and an event in your code behind which you wished to wire up programmatically using an anonymous method it would look similar to the following:

Anonymous Method

protected void Page_Init(object sender, EventArgs e)
{
	btnGo.Click += delegate(object sender, EventArgs e)
		         {
			lblDate.Text = DateTime.Now.ToString();
		         }
}


This is all very nice and tidy yes? But a Lambda Expression can make this ten times easier to write and look ten times more tidy.

This example does the exact same as our anonymous method example only using Lambda Expressions

Lambda Expression

1
2
3
4
protected void Page_Init(object sender, EventArgs e)
{
	btnGo.Click += (object sender, EventArgs e) => lblDate.Text = DateTime.Now.ToString();
}

If we break this statement down and explain each individual part it will become easier to understand

  • btnGo.Click – This is the Event that when takes place, the remaining statement will be executed.
  • (object sender, EventArgs e) - This is the parameters of the EventHandler you are creating.
  • => – This stands for “Goes Into” and is used to seperate a list of method parameters from the method itself.
  • lblDate.Text – This is the label control of which we will amend the Text property.
  • DateTime.Now.ToString() – This represents the current date in a string format.
posted under ASP.NET
One Comment to

“Basic Lambda Expressions Using ASP.NET 3.5 and C#”

  1. On August 21st, 2009 at 4:39 pm geeks Says:

    Interesting,

    Great lambda expression learning

    Thanks for writing, most people don’t bother.

Email will not be published

Website example

Your Comment: