Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 99 - Lambda expression in c#

Suggested Videos 
Part 96 - How to resolve a deadlock in a multithreaded program
Part 97 - Performance of a multithreaded program
Part 98 - Anonymous methods in c#



In this video we will discuss, what lambda expressions are with an example. We will be working with the same example that we worked with in Part 98.



Anonymous methods and Lambda expressions are very similar. Anonymous methods were introduced in C# 2 and Lambda expressions in C# 3. 

To find an employee with Id = 102, using anonymous method
Employee employee = listEmployees.Find
    (delegate(Employee Emp) { return Emp.ID == 102; });

To find an employee with Id = 102, using lambda expression
Employee employee = listEmployees.Find(Emp => Emp.ID == 102);

You can also explicitly specify the Input type but not required
employee = listEmployees.Find((Employee Emp) => Emp.ID == 102);

Notice that with a Lambda expression you don't have to use the delegate keyword explicitly and you don't have to specify the input parameter type explicitly. The parameter type is inferred. Lambda expressions are more convenient to use than anonymous methods. Lambda expressions are particularly helpful for writing LINQ query expressions.

=> is called lambda operator and read as GOES TO.

In most of the cases Lambda expressions supersedes anonymous methods. To my knowledge, the only time I prefer to use anonymous methods over lambdas is, when we have to omit the parameter list when it's not used within the body. 

Anonymous methods allow the parameter list to be omitted entirely when it's not used within the body, where as with lambda expressions this is not the case.

For example, with anonymous method notice that we have omitted the parameter list as we are not using them within the body
Button1.Click += delegate
{
    MessageBox.Show("Button Clicked");
};

The above code can be rewritten using lambda expression as shown below. Notice that with lambda we cannot omit the parameter list.
Button1.Click += (eventSender, eventAgrs) =>
{
    MessageBox.Show("Button Clicked");
};

1 comment:

  1. You are my C# guru.Please keep on posting new articles and videos.Good luck and thank u.

    ReplyDelete

It would be great if you can help share these free resources