A simple example of using lambda in C#:
// Simple method definition - before lambdas:
int Square(int x) => x * x;
// Lambda equivalent (more concise):
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
In the above example x => x * x
is a lambda expression that takes an integer argument and returns its square.
The method before lambdas defined using the Func generic type allows for specifying input/output types explicitly.
Lambda expressions can also contain multiple statements:
Func<int, int> addTenThenSquare = x => { return (x + 10) * (x + 10); };
Console.WriteLine(addTenThenSquare(3)); // Output: 169
In this case, the lambda expression consists of two expressions separated by a semicolon. The first part (x + 10)
is an intermediate variable with value x+10
, and then we square it as shown in parenthesis.
Additionally, lambdas can be used to create delegates:
Action greet = name => Console.WriteLine($"Hello {name}!");
greet("Alice"); // Output: Hello Alice!
Here the lambda expression is assigned directly into an Action delegate which represents a method that takes no
parameters and returns void. The lambda itself includes one parameter (name
) with no return type, as denoted by
Action<>
.
Lambdas become particularly powerful when working together in collections using LINQ (Language-Integrated Query),
where they can succinctly express queries over sequences of objects:
List<int> numbers = new List<int>{ 1, 2, 3, 4, 5 };
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
foreach (int number in evenNumbers) {
Console.WriteLine(number); // Output: 2 and then 4.
}
The lambda expression used here is implicit within the select
clause of LINQ. It represents a transformation
that extracts each item from an input sequence (numbers
) but only if it satisfies certain conditions, in this case being even.
In summary, lambdas are syntactic sugar for anonymous functions or methods and they provide many benefits such as brevity when writing code inline with other expressions like those found within LINQ queries. They allow developers to write more readable and concise C# codes while preserving the full power of object-oriented programming features that come from delegates.