blog

Home / DeveloperSection / Blogs / Lambda Expression in C#

Lambda Expression in C#

Amit Singh7217 01-Jan-2011

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);
            Console.ReadLine();
            //Createan expression tree type
            //Thisneeds System.Linq.Expressions
            Expression<funDelegate> ExpDel = Exp => Exp / 12;
        }

Output:
Output 10
Note:


The => operator has the same precedence as assignment (=) and isright-associative.

Lambdas are used in method-based LINQ queries as arguments to standard queryoperatormethods such as Where.


Updated 18-Sep-2014

Leave Comment

Comments

Liked By