Lambda Expressions
Learn the => syntax for writing compact, inline anonymous functions in C#.
What is a Lambda Expression?
A lambda expression is a compact way to write an anonymous (unnamed) function inline, most often assigned to a delegate type like Func or Action, or passed directly to a method.
Lambda Syntax
// Traditional methodstatic int Square(int x) => x * x;
// Equivalent lambda expressionFunc<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 25
// Multiple parameters need parenthesesFunc<int, int, int> add = (a, b) => a + b;
// Multi-statement lambdas use braces and an explicit returnFunc<int, string> classify = n =>{ if (n % 2 == 0) return "even"; return "odd";};Lambdas with Collections
Lambdas shine when passed to collection methods that accept a delegate — you'll see this pattern constantly once you learn LINQ in the next lesson.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
List<int> evens = numbers.Where(n => n % 2 == 0).ToList();bool anyBig = numbers.Any(n => n > 10);
Console.WriteLine(string.Join(", ", evens));Console.WriteLine(anyBig);Output
Click Run to see what this code prints.
Captured Variables
A lambda can reference variables from its enclosing scope — this is called "closing over" a variable, and the lambda keeps that variable alive as long as it needs it.
int threshold = 3;Func<int, bool> isAboveThreshold = n => n > threshold;
Console.WriteLine(isAboveThreshold(5)); // Truethreshold = 10;Console.WriteLine(isAboveThreshold(5)); // False — uses the updated thresholdFAQs
They're closely related — lambdas are a more concise syntax that largely replaced the older `delegate(...) { ... }` anonymous method syntax.
Summary
- Lambda expressions write small, inline functions using =>.
- They're commonly assigned to Func/Action or passed to collection methods.
- Lambdas can capture variables from their enclosing scope.