Definition: "Lambda Expression" is an anonymous function, an efficient expression similar to functional programming.
Benefits: Lambda simplifies the use of anonymous delegations and reduces the amount of code that needs to be written in development.
Writing: All Lambda expressions use the Lambda operator =>, which is read as "goes to". On the left side of the Lambda operator are the input parameters (if any), and on the right side are expressions or statement blocks. The Lambda expression x => x * x is read as "x goes to x times x".
Note: (left) When the input parameter is 1, braces can be omitted. (right) when the expression has only one sentence, braces and return statements can be omitted.
The specific grammatical form is as follows.
Access modifier Modifier Return value type Method name (parameter list) => Expression;
public static int Add(int a, int b) => a + b;
General lambda expressions are used to create delegate or expression tree types.
delegate int del(int i);
del myDelegate = x => x*x; //The x here represents the parameter of type int, and c# will automatically lock the type.
The essence of Lambda is method (anonymous method).
Closure
The lambda expression allows access to variables outside the lambda expression block, which is called a closure.
int lamValue = 5;
Func<int,int> sum = x => x+lamValue;
Doing so is dangerous because when the value of the external variable changes, it will also affect the result of the sum.
Lambda internal implementation process
The compiler creates an anonymous class that has a constructor to pass external variables.
public class AnonymousClass{ public int lamValue; public AnonymousClass(int lamValue){ = lamValue; } public int AnonymousMethod(int x) => x+lamValue; }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.