Monday, June 30, 2008

Lambda Expression

Lambda Expression -- introduced by Microsoft in C# 3.0 is a very fascinating topic. It has been extensively used in LINQ(Language Intergrated Query).

So, what is Lambda Expression?

Lambda Expression is basically nothing but an anonymous function.

In .Net 1.1 we used to create delegates using delegate type. Delegate is a type safe datatype which contains a reference to a function.
Eg:


.Net 2.0 introduced the concept of Anonymous delegates. what is means is you can write the whole function inline. This makes the code more readable and you don't have to define instance or static methods.
Eg:


As you can see the code is readable and concise.

In C# 3.0 the concept of anonymous delegates has been taken to the next level by adding lambda expression.

Lambda expression uses an operator ( =>) which should be read as "goes to".
Eg:


As you can see the code is very elegant and the IL(intermediate language) generated by all the 3 ways of using delegates is the same. So the point to understand here is that the complier will generate exactly the same IL for all the 3 implementations so we don't need a new runtime for executing this code. .Net 2.0 runtime will be able to execute this code for us.

Lambda's can be expression or statements. Lambda statement are nothing but a group of c# statements clubbed together.

IL generate by instance methods:

IL generated by anonymous delegates (.Net 2.0)


IL generated by Lambda Expression


Click here to download the SourceCode:


I hope this will help you understand what Lambda expressions are.

Thanks,
Yash

0 comments: