Thursday, June 14, 2012

Lambda Expressions in .Net 3.0


Lambda Expressions can be seen as version 3.0 of Delegate.
In .Net 1.1, delegates were initialized by mapping them to explicit method names which are already defined. To more about delegates refer to the post Delegates in C#.

In .Net 2.0, Anonymous methods helped us to define the methods while initializing the delegates. To more about Anonymous methods refer to the post Anonymous Methods.

In .Net 3.0 Lambda expressions further simplify delegate programming by adding expression based syntax.

Unlike Anonymous Methods, usage of Lambda expressions are not restricted just to delegate programming, the evaluate either to a delegate or to an expression based on the type assigned in the left hand side.

Lambda expressions use the Lambda operator =>

Syntax
(Input Parameters) => Expression (or) Statement Block

Let us understand Lambda Expression with an example.  

First let us declare a Delegate
delegate int AddNumberDelegate(int Number1, int Number2);

Delegates in .Net 1.1
In .Net 1.1 to initialize this delegate, we need to declare a function which will match the signature of the delegate, and later assign the function while initializing the delegate as follows.
private int AddNumber(int Number1, int Number2)
{
    return Number1 + Number2;
}
// Delegates in .Net 1.1
// Delegate Initialization
AddNumberDelegate Delegate_v1 = new AddNumberDelegate(AddNumber);
// Delegate Call
Response.Write(".Net 1.1 Delegate: " + Delegate_v1(1, 2));

Delegates in .Net 2.0 (Anonymous Methods)
// Delegates in .Net 2.0
AddNumberDelegate Delegate_v2 = delegate(int Number1, int Number2)
                                {
                                    return Number1 + Number2;
                                };
// Delegate Call
Response.Write(".Net 2.0 Delegate: " + Delegate_v2(1, 2));

Delegates in .Net 3.0 (Lambda Expressions)
//
// Delegates in .Net 3.0
AddNumberDelegate Delegate_v3 = (Number1, Number2) => Number1 + Number2;
// Delegate Call
Response.Write(".Net 3.0 Delegate : " + Delegate_v3(1, 2));


As you could see, the number of lines of code requires to do delegate programming is coming down with the improvements in the .Net Framework versions

All the three versions produce the same output
.Net 1.1 Delegate: 3
.Net 2.0 Delegate: 3
.Net 3.0 Delegate: 3

The use of Lambda Expressions does not end with just delegate programming, Unlike Anonymous methods, Lambda Expressions can also be used to evaluate expression trees. Lambda expressions are also extensively used in LINQ programming.

Search Flipkart Products:
Flipkart.com

No comments: