Lambda expressions in C# provide a concise way to create anonymous functions. They are a powerful feature introduced in C# 3.0, enabling developers to write more expressive and functional code.
Lambda expressions are inline, anonymous functions that can be used to create delegates or expression tree types. They allow you to write local functions that can be passed as arguments or returned as values from other functions.
The basic syntax of a lambda expression consists of input parameters (if any), the lambda operator =>
, and an expression or statement block.
(parameters) => expression
For single-parameter lambda expressions, parentheses are optional:
parameter => expression
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
In this example, we define a lambda expression that squares a number. The Func<int, int>
delegate takes an integer input and returns an integer output.
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 7)); // Output: 10
Here, we create a lambda expression that adds two numbers. The delegate takes two integer inputs and returns their sum.
Lambda expressions are frequently used in various scenarios:
One of the most common applications of lambda expressions is in LINQ queries. They provide a concise way to define predicates and projections.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
// Output: 2, 4, 6, 8, 10
In this example, the lambda expression n => n % 2 == 0
is used to filter even numbers from the list.
Lambda expressions are a powerful feature in C# that enable more expressive and functional programming styles. They are particularly useful in scenarios involving delegates, LINQ queries, and event handling. By mastering lambda expressions, you can write more concise and efficient code in your C# applications.