Lambda Expressions in C#
Lambda Expressions in C#
=========================
Lambda expressions are an important feature in C# that allow for writing anonymous
methods in a concise and readable manner. They are used primarily with delegates and
LINQ queries.
Definition and Syntax
---------------------
A lambda expression is defined using the lambda operator `=>`, which separates the input
parameters on the left side from the expression or block of statements on the right side.
Syntax:
(parameters) => expression
or
(parameters) => { statements }
Examples:
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // Output: 7
If there is only one parameter, parentheses are optional:
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Usage in LINQ
-------------
Lambda expressions are heavily used in LINQ (Language Integrated Query) for filtering,
selecting, and transforming data.
Example:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Capturing Outer Variables
-------------------------
Lambda expressions can access variables from the outer method (closure).
Example:
int multiplier = 5;
Func<int, int> multiply = x => x * multiplier;
Console.WriteLine(multiply(3)); // Output: 15
Action vs Func Delegates
------------------------
- Func<> is used when the lambda expression returns a value.
- Action<> is used when it does not return a value.
Example:
Action<string> greet = name => Console.WriteLine("Hello " + name);
greet("Alice");
Benefits of Lambda Expressions
------------------------------
- More concise code
- Better readability
- Useful in event handling and LINQ
- Replaces verbose anonymous method declarations
Limitations
-----------
- Can reduce readability if overused or too complex
- Debugging can be harder compared to named methods
Conclusion
----------
Lambda expressions in C# provide a powerful and elegant way to define inline functions
and simplify code, especially when working with collections and LINQ. Understanding how
to use them effectively enhances the developer's ability to write cleaner and more efficient
C# programs.