Home > Article > Backend Development > What are Lambda expressions in C#?
Lambda expressions are a better way to represent anonymous methods. Both anonymous methods and lambda expressions allow you to define method implementations inline, however, anonymous methods explicitly require you to define the method's parameter types and return type.
An expression with an expression as its expression lambda body: (input−parameters) => Expression
Statement lambda with statement block as its body:
(input−parameters) => {
Any lambda expression can be converted to a delegate type. The delegate type that a lambda expression can be converted to is defined by the types of its parameters and return value. If the lambda expression does not return a value, it can be cast to one of the Action delegate types; otherwise, it can be cast to one of the Func delegate types.
static void Main(string[] args){ Func<int, int> square = x => x * x; Console.WriteLine(square(5)); Console.ReadLine(); }
=> A lambda expression with an expression on the right side of the operator is called an expression lambda. Expression lambda returns the result of an expression in the following basic form
Action line = () => Console.WriteLine();
Func
Func
Func
C# In 7.0, the C# language provides built-in support for tuples. You can provide a tuple as an argument to a lambda expression, and your lambda expression can also return a tuple.
Variables introduced in lambda expressions are not visible in the enclosing method.
A lambda expression cannot capture in, ref, or out parameters directly from the enclosing method.
The return statement in a lambda expression does not cause the enclosing method to return.
If the target of the jump statement is outside the lambda expression block, the lambda expression cannot contain a goto, break, or continue statement. It is also an error to use a jump statement outside a lambda expression block if the target is inside the lambda expression block.
The above is the detailed content of What are Lambda expressions in C#?. For more information, please follow other related articles on the PHP Chinese website!