Lambda expression is an inline expressions that can be used where a delegate type is expected. It is a anonymous function that is use to create delegates or expression trees excepts that lambda expression are more concise and flexible than anonymous method.
In C# 3.0 and later lambda expression supersede anonymous method. Lambda expression are derived from Church's -calculus theory of compatibility in 1941. Lambda expression are based on functional programming and also lambda expressions also converted into functional interfaces. Lambda expression used lambda operator "=>" which also known as " goes to ".The => operator has the same precedence as assignment (=) and is right associative.
In Lambda expression the left part of the expression specifies input parameter and right part specifies an expression or statements. For example expression z => z * z specifies that left side variable z is a parameter and right side part is an expression that return square of z.
The benefit of lambda expression is first it reduced typing means we need not to define the function, it return type and access modifier and second benefit is we need not to look elsewhere for method definition while reviewing the code.
How lambda expression can work lets take an examples. A lambda expression is an anonymous function that is use to create delegates. So to evaluate z => z * 10using both anonymous method as well as lambda expression.
When using an anonymous method -
ChangeInt myDelegate = new ChangeInt( delegate(int z) { return z * 10; } ); Console.WriteLine("{0}", myDelegate(5));
When using an lambda expression -
ChangeInt myDelegate = z => z * 10; Console.WriteLine("{0}", myDelegate(5));
If you wanted to, you could have specified the type of the argument, as follows:
The lambda expression z => z * 10 is read "z goes to 10 times z." This reduced the number of lines and the output is still the same.
Lambda expression can be generalized as ( input parameter ) => ( expression/statement ). Expression or Statement block also known as Expression Lambdas.
Different Type of Lambda Expression -
1.When lambda has one input parameter.
Examples - z => z * z; y => y + 5; x => return x + 9;
2.When lambda has two or more input parameter, then these parameter are separated by commas and enclosed in parentheses.
Examples - (x,y) => x == y; (int x, int y) => return x > y
3.When lambda has zero input parameter than we used empty parentheses.
0 Comment(s)