C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Lambda Expressions

C# Lambda Expressions

Lambda expressions are anonymous functions with a concise syntax — the backbone of LINQ and functional C#.

1 - Syntax

// No parameters
Action greet = () => Console.WriteLine("Hello!");

// One parameter (parentheses optional)
Func<int, int> square = x => x * x;

// Multiple parameters
Func<int, int, int> add = (a, b) => a + b;

// Statement body (multiple lines)
Func<int, string> classify = n =>
{
    if (n < 0)  return "negative";
    if (n == 0) return "zero";
    return "positive";
};

2 - Capturing Variables (Closures)

int multiplier = 3;
Func<int, int> times = x => x * multiplier; // captures multiplier

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

3 - Lambdas with LINQ

var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evens  = numbers.Where(n => n % 2 == 0);
var squared = numbers.Select(n => n * n);
var sum    = numbers.Where(n => n > 5).Sum();
var sorted = numbers.OrderByDescending(n => n);

Console.WriteLine(string.Join(", ", evens));   // 2, 4, 6, 8, 10
Console.WriteLine(sum);                        // 40

Note: Lambdas capture variables by reference, not by value. If you use a loop variable inside a lambda that is called later, all lambdas will see the final value of the variable, not the value at capture time. Copy loop variables to a local variable first if this is a concern.

-Tip-

C# {"id":45,"topic_id":3,"name":"C# Delegates and Events","slug":"c-delegates-and-events","image":null,"description":"<p>Understand delegates, lambda expressions, Func\/Action, and the event pattern in C#.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":14,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: