Lambda expression

A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambdaexpressions can be used mostly to create delegates or expression tree types.Lambda expression uses lambda operator => and read as 'goes to' operator.

Left side of this operator specifies the input parameters and contains theexpression or statement block at the right side.
The basic syntax is:

(commaseparated parameters)=>
 {semicolon terminated statement list;}


Where The=> symbol is read “becomes” to indicate that the parameters are transformedinto the actions.

A lambda expression shares all its characteristics withanonymous methods.

Example: Exp = Exp/10;
Now, let see how we can assign the above to a delegate and create an expressiontree:

//This needs System.Linq.Expressions

using System.Linq.Expressions;


delegate int funDelegate(int intMyNum);

        static void Main(string[] args)


            //assignlambda expression to a delegate:

            funDelegatemyDelegate = Exp => Exp / 12;

            intnVal = myDelegate(120);

            Console.WriteLine("Output {0}", nVal);


            //Createan expression tree type

            //Thisneeds System.Linq.Expressions

            Expression<funDelegate> ExpDel = Exp => Exp / 12;



Output 10

The => operator has the same precedence as assignment (=) and isright-associative.
Lambdas are used in method-based LINQ queries as arguments to standard queryoperator methods such as Where.


Leave Comment