How to Use Lambda Expressions in C# - Simple Guide
In C#, a
lambda expression is a concise way to write anonymous functions using the syntax (parameters) => expression. You use lambdas to create inline functions for delegates or LINQ queries easily.Syntax
A lambda expression uses the => operator to separate parameters and the function body.
- Parameters: Input values, can be typed or inferred.
- => : Lambda operator, means 'goes to'.
- Expression or block: The code executed, can be a single expression or multiple statements in braces.
csharp
(parameters) => expression // Example: int x => x * x;
Example
This example shows how to use a lambda to square numbers in a list and print the results.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Use lambda to select squares var squares = numbers.Select(x => x * x); foreach (var square in squares) { Console.WriteLine(square); } } }
Output
1
4
9
16
25
Common Pitfalls
Common mistakes when using lambdas include:
- Forgetting parentheses for multiple parameters, e.g.,
x, y => x + yis invalid; use(x, y) => x + y. - Using statement blocks without braces when needed.
- Confusing lambda expressions with method groups.
csharp
/* Wrong: Missing parentheses for multiple parameters */ // var add = x, y => x + y; // Error /* Correct: Use parentheses */ var add = (x, y) => x + y;
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Single parameter | No parentheses needed | x => x * 2 |
| Multiple parameters | Use parentheses | (x, y) => x + y |
| No parameters | Empty parentheses | () => 42 |
| Expression body | Single expression returns value | x => x * x |
| Statement body | Use braces and return | (x) => { return x + 1; } |
Key Takeaways
Use
=> to create concise anonymous functions called lambda expressions.Parentheses are required for zero or multiple parameters but optional for one parameter.
Lambdas can be used anywhere a delegate or expression tree is expected, like LINQ.
Watch out for syntax errors with parameters and statement blocks.
Lambdas help write cleaner, shorter code for inline functions.