Lamda expression is an anonymous function which can contain expressions and statement. It can be used in delegates. Lamda expression use Lamda(=>) operator.
Consider the following example
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- delegate int TestDelegate(int a,int b);
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("e");
- TestDelegate Deltest = (x, y) => x + y;
- var result = Deltest(5, 10);
- Console.WriteLine(result);
- }
- }
- }
TestDelegate Deltest = (x, y) => x + y;
The left side of the Lamda operator are the input parameter and the right side of the Lamda operator are the expression.
Here the expression has two input parameters (x,y) and returns int, So it conforms to the delegate when we call
Deltest(5,10);
we get the result 15.
But if we call DelTest(5.0,10) it will generate compile time error. Because it will violate the
TestDelegate signature.
Note: All the restrictions applied for anonymous method also be applied for Lamda expression.
Expression Lamda:
A lamda expression with an expression on the right hand side is called the expression lamda.
(x,y)=>x+y
is an expression lamda.
Statement Lamda
Statement lamda is like expression lamda with that statement is enclosed with braces.
The general rules for lambdas are as follows:
-
The lambda must contain the same number of parameters as the delegate type.
-
Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
-
The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.
Variable Scope in Lamda expression
The following rules apply to variable scope in lambda expressions:
-
A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.
-
Variables introduced within a lambda expression are not visible in the outer method.
-
A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
-
A return statement in a lambda expression does not cause the enclosing method to return.
-
A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.
No comments:
Post a Comment