What is Lambda expression in C#?


Lambda expression is a better way to represent an anonymous method. Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method.

Expression lambda that has an expression as its body: (input−parameters) => expression

Statement lambda that has a statement block as its body: (input−parameters) => { <sequence−of−statements> }

Any lambda expression can be converted to a delegate type. The delegate type to which a lambda expression can be converted is defined by the types of its parameters and return value. If a lambda expression doesn't return a value, it can be converted to one of the Action delegate types; otherwise, it can be converted 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. An expression lambda returns the result of the expression and takes the following basic form

Action line = () => Console.WriteLine();

Func<double, double> cube = x => x * x * x;

Func<int, int, bool> testForEquality = (x, y) => x == y;

Func<int, string, bool> isTooLong = (int x, string s) => s.Length > x;

C# 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 within a lambda expression are not visible in the enclosing method.

A lambda expression cannot directly capture an in, ref, or out parameter from the enclosing method.

A return statement in a lambda expression doesn't cause the enclosing method to return.

A lambda expression cannot contain a goto, break, or continue statement if the target of that jump statement is outside the lambda expression block. It's also an error to have a jump statement outside the lambda expression block if the target is inside the block.

Updated on: 05-Nov-2020

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements