17
Lesson 17 of 35 · OOP

Lambda Expressions

Lambda expressions are anonymous functions—compact inline code that can be passed as arguments, stored in variables, and used wherever a delegate or expression tree is expected.

Lambda Syntax

A lambda uses the arrow operator =>. The left side lists parameters; the right side is an expression or block body.

Lambda syntax Lambdas.cs
// Expression lambda (single expression result)
Func square = x => x * x;
Console.WriteLine(square(5)); // 25

// Statement lambda (block body)
Func compare = (a, b) =>
{
    if (a > b) return $"{a} > {b}";
    if (a < b) return $"{a} < {b}";
    return "equal";
};
Console.WriteLine(compare(3, 7)); // 3 < 7

Lambdas with Collections

Lambdas are most powerful when combined with collection methods like Where, Select, OrderBy, and Any from LINQ.

LINQ lambdas LinqLambda.cs
var numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evens  = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);
var sorted  = numbers.OrderByDescending(n => n);

Console.WriteLine(string.Join(", ", evens));   // 2, 4, 6, 8, 10
Console.WriteLine(string.Join(", ", squares)); // 1, 4, 9, 16...

Closures

A lambda can capture variables from the enclosing scope—this is called a closure. The captured variable is shared, not copied.

Closure Closure.cs
int multiplier = 3;
Func triple = x => x * multiplier;
Console.WriteLine(triple(5));  // 15

multiplier = 10;
Console.WriteLine(triple(5));  // 50 — captures reference!