65.9K
CodeProject is changing. Read more.
Home

Lambda Simplified

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.41/5 (55 votes)

Oct 18, 2010

CPOL
viewsIcon

99652

The article simplifies the understanding of Lambda expression

Introduction

Lambda expressions in C# are simple to use, but when you see Lambda expression for the first time, it will be so confusing. The article simplifies the understanding of a Lambda expression by taking you through a code evolution tour.

Evolution

In a typical .NET 1.0 code, the simple event handler can be written as follows:

public Form1()
{
   InitializeComponent();
   this.button1.Click += new System.EventHandler(this.button1_Click);
}

private void button1_Click(object sender, EventArgs e)
{
   MessageBox.Show("Hello Events");
}

By using .NET 2.0 Anonymous method, we can simplify the code by:

  • Removing method name
  • Bringing it closer to event handler (move the code within the {})
  • No need to add Event Handler. You can use Delegate keyword to create a delegate object of the anonymous method.
public Form1()
{
   InitializeComponent();
   this.button1.Click += new System.EventHandler(this.button1_Click);

    private void button1_Click delegate (object sender, EventArgs e)
    {
        MessageBox.Show("Hello Events");
    }
}

So if you use anonymous method, the code looks like:

public Form1()
{
   InitializeComponent();
   this.button1.Click += delegate (object sender, EventArgs e)
                         {
                             MessageBox.Show("Hello Events");
                         };
}

By using .NET 3.0 lambda syntax, the code is even more simplified.

  • You can remove delegate keyword
  • No need to explicitly state the param types, as the compiler can inference type types
  • When we have single expression, no need for {} also.
  • and introduce => to split the param and method expression.
public Form1()
{
   InitializeComponent();
   this.button1.Click += delegate (object sender, EventArgs e) =>
                         {
                             MessageBox.Show("Hello Events");
                         };
}

So now with Lambda syntax, the same code simplified as below:

public Form1()
{
   InitializeComponent();
   this.button1.Click += (sender, e) => MessageBox.Show("Hello Events");
 }

Conclusion

The article try to simplify the understanding of Lambda expression. To know more about Lambda, check this MSDN article.