expressionLambda: the lambda expression on the right side of the + = operator is called an expression lambda
(input parameters) = expression//expressions Lambda
For example
(x, y) = x = = Y
Statementthe right side of the lambda:=> operator is a statement block, and the statement is enclosed in curly braces
(input parameters) = {statement;} Statement Lambda
For example:
(x, y) = = {return x = = y;}
What's the difference between the two, in addition to the wording, use the following code as a test
Using system;using system.collections.generic;namespace linqtest{ class program { static void Main ( String[] args) { list<int> List = new List<int> {1, 3, 2, 4}; var resultusingexpressionlambda = list. FindAll (P = p < 3); Console.WriteLine ("Use expression lambda:"); foreach (var item in Resultusingexpressionlambda) { Console.WriteLine (item); } var resultusingstatementlambda = list. FindAll (p = = { return P < 3; }); Console.WriteLine ("Use statement lambda:"); foreach (var item in Resultusingstatementlambda) { Console.WriteLine (item); } } }
The code is simple to use the expression lambda and the statement lambda to find the number less than 3, and then output, the result is as follows
The output is the same.
View the post-compilation code
It seems that the compiler has done the same, the code is the same, in this case, then add a line of code in the statement lambda, Console.WriteLine (p); This will not generate the same code.
Console.WriteLine (P.tostring ());
Using system;using system.collections.generic;namespace linqtest{ class program { static void Main ( String[] args) { list<int> List = new List<int> {1, 3, 2, 4}; var resultusingexpressionlambda = list. FindAll (P = p < 3); Console.WriteLine ("Use expression lambda:"); foreach (var item in Resultusingexpressionlambda) { Console.WriteLine (item); } var resultusingstatementlambda = list. FindAll (p = = { Console.WriteLine (P);//This is the newly added return P < 3; }); Console.WriteLine ("Use statement lambda:"); foreach (var item in Resultusingstatementlambda) { Console.WriteLine (item); } } }
Re-View the post-compilation code
And look at the IL code.
As you can see, whether it's an expression lambda or a statement lambda, and finally a method, the resulting method is and then assigns the method to the delegate variable, which is this part:
Therefore, when assigning a value to a delegate variable, the expression lambda and the statement lambda do not write the same, but the compiler generates a method at the end. There is also a different point in which an expression lambda can be converted to an expression tree of type expression<t>, whereas a statement lambda can not
Expression<func<int, int, int>> expression = (A, b) = + A + b;//correct expression<func<int, int, int>> ; Expression1 = (A, b) = = {return a + B;};//error, unable to convert lambda expression with statement body to expression tree
(go) expressions in lambda expressions Lambda and statement lambda differences