Thursday, December 11, 2008

Minimize your code using Lambda Expressions in C# 3.0

In early days ,if we want to show a message box on a button click ,we had to do so many things.
First we have to subscribe to the click event.Then in the event handler we have to write code to show message box.Atleast it will took 3 lines of code.(Most of the code is auto generated by VisualStudio).

btnObj.Click += new EventHandler(btnObj_Click);

void btnObj_Click(object sender, EventArgs e)

{

MessageBox.Show("Clicked :In EventHandler method");

}
With the introduction of anonymous methods in C# 2.0 it became very easy and takes only one line of code.

btnObj.Click += delegate(object sender,EventArgs args){ MessageBox.Show("Clicked :In Anonymous delegate"); };

Later in C# 3.0 the Lambda expressions were introduced which again simplified the coding.

btnObj.Click += (sender, args) => MessageBox.Show("Clicked :In Lambda Expression");



No comments: