Lambda Expressions in CSharp
Lambda Expressions in CSharp
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.
---------------------
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
Examples:
Func<int, int, int> add = (a, b) => a + b;
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 };
-------------------------
Lambda expressions can access variables from the outer method (closure).
Example:
int multiplier = 5;
Console.WriteLine(multiply(3)); // Output: 15
------------------------
Example:
Action<string> greet = name => Console.WriteLine("Hello " + name);
greet("Alice");
- Better readability
Limitations
-----------
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.