Lambda Expressions in C#
Lambda expressions are a concise way to represent anonymous functions in C#. They allow you to write inline functions without explicitly defining a method. Lambda expressions are particularly useful in scenarios where you need to pass a small piece of code as a parameter to a method, such as with LINQ queries.
Key Concepts
Lambda expressions in C# are based on three main concepts:
- Expression Lambda: A lambda expression that contains a single expression.
- Statement Lambda: A lambda expression that contains a block of statements.
- Lambda Parameters: The input parameters of the lambda expression.
Expression Lambda
An expression lambda consists of a single expression and returns the result of that expression. The syntax is:
(input-parameters) => expression
Example
Func<int, int> square = x => x * x; Console.WriteLine(square(5)); // Output: 25
In this example, the lambda expression x => x * x
takes an integer x
as input and returns its square.
Statement Lambda
A statement lambda contains a block of statements enclosed in curly braces. The syntax is:
(input-parameters) => { statement-block }
Example
Action<int> printSquare = x => { int result = x * x; Console.WriteLine(result); }; printSquare(5); // Output: 25
In this example, the lambda expression x => { int result = x * x; Console.WriteLine(result); }
takes an integer x
as input, calculates its square, and prints the result.
Lambda Parameters
Lambda expressions can take zero or more parameters. If there is only one parameter, the parentheses can be omitted. If there are no parameters, an empty pair of parentheses is used.
Example
// No parameters Action printHello = () => Console.WriteLine("Hello"); printHello(); // Output: Hello // One parameter (parentheses optional) Func<int, int> cube = x => x * x * x; Console.WriteLine(cube(3)); // Output: 27 // Multiple parameters Func<int, int, int> add = (x, y) => x + y; Console.WriteLine(add(3, 4)); // Output: 7
In these examples, the lambda expressions demonstrate different ways to handle parameters, including no parameters, a single parameter, and multiple parameters.
Conclusion
Lambda expressions in C# provide a powerful and concise way to write anonymous functions. They are particularly useful in scenarios where you need to pass a small piece of code as a parameter to a method. By understanding expression lambdas, statement lambdas, and lambda parameters, you can write more expressive and flexible code.