Letβs go through lambda expressions in C# β a concise way to define anonymous functions.
π 1. What is a Lambda Expression?
-
A lambda expression is an inline, anonymous function
-
Can be assigned to delegates or Func/Action types
-
Uses the
=>
(goes to) operator
Basic Syntax
(parameters) => expression
- If multiple statements, use curly braces
{}
π 2. Example with a Delegate
public delegate int MathOperation(int x, int y);
MathOperation add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // 8
-
(a, b)
β parameters -
a + b
β expression returned -
=>
separates parameters from body
π 3. Lambda with Multiple Statements
MathOperation multiply = (a, b) =>
{
int result = a * b;
return result;
};
Console.WriteLine(multiply(4, 5)); // 20
- Use curly braces and return for multiple statements
π 4. Using Lambdas with Func and Action
-
Func<T1, T2, TResult> β returns a value
-
Action<T1, T2> β no return value
Func Example
Func<int, int, int> subtract = (x, y) => x - y;
Console.WriteLine(subtract(10, 4)); // 6
Action Example
Action<string> greet = name => Console.WriteLine("Hello " + name);
greet("Alice"); // Hello Alice
π 5. Lambda Expressions with LINQ
- Lambdas are heavily used in LINQ queries
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var n in evenNumbers)
Console.WriteLine(n); // 2, 4
n => n % 2 == 0
is the predicate lambda
π 6. Advantages of Lambda Expressions
-
Concise β no need to define separate methods
-
Readability β especially with LINQ queries
-
Type Inference β compiler infers parameter types
-
Functional Programming Style β easy to chain operations
π 7. Summary Table
Feature | Description |
---|---|
Syntax | (parameters) => expression |
Func | Delegate that returns a value |
Action | Delegate that does not return a value |
Use Cases | LINQ queries, callbacks, inline methods |
Multi-line Body | Use { } and return |
β Tip:
-
Use lambda expressions for short inline methods
-
Combine with LINQ for powerful, readable data manipulation