C# Lambda Expressions
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →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.
What are Lambda Expressions?
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.
Basic Syntax
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
Examples of Lambda Expressions
1. Simple Lambda 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.
2. Lambda with Multiple Parameters
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.
Common Use Cases
Lambda expressions are frequently used in various scenarios:
- With LINQ queries for filtering, sorting, and transforming data
- As event handlers or callbacks
- In functional programming patterns
- For creating short, inline functions
Lambda Expressions in LINQ
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.
Best Practices and Considerations
- Keep lambda expressions short and simple for better readability
- Use lambda expressions to reduce code duplication
- Consider using lambda expressions instead of anonymous methods for more concise code
- Be aware that extensive use of lambda expressions can make debugging more challenging
Conclusion
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.