C# Intermediate: OOP, Interfaces & Events

Lesson 6 of 7

Lambda Expressions, Func & Action

A lambda expression is a compact, inline way to write a method, most useful when you need to pass a small piece of behavior somewhere, like a callback or a LINQ predicate.

Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7

Action<string> log = message => Console.WriteLine($"[LOG] {message}");
log("Server started");

List<int> scores = new List<int> { 55, 82, 91, 40 };
List<int> passing = scores.Where(s => s >= 70).ToList();

Func and Action

  • Func<T1, ..., TResult> is a built-in delegate type for a method that returns a value, the last type parameter is always the return type. Func<int, int, int> takes two ints and returns an int.
  • Action<T1, ...> is the same idea for a method that returns nothing (void). Action<string> takes one string and returns nothing, plain Action takes no parameters at all.
  • Both are just delegate types the .NET library already defines, so you don't need your own delegate declaration for common shapes.

Lambda syntax

  • (a, b) => a + b is shorthand for a method taking a and b, and returning a + b.
  • A single parameter can drop the parentheses: s => s >= 70.
  • A lambda can capture variables from its surrounding scope (a closure), a lambda defined inside a method can still use that method's local variables even after being passed elsewhere.

📝 Lambdas, Func & Action Quiz

Passing score: 70%
  1. 1.Which built-in delegate type represents a method that returns void?

  2. 2.In Func<int, int, int>, the ____ type parameter is always the return type.

  3. 3.A lambda expression can capture and use variables from its surrounding scope.