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 twoints and returns anint.Action<T1, ...>is the same idea for a method that returns nothing (void).Action<string>takes onestringand returns nothing, plainActiontakes no parameters at all.- Both are just delegate types the .NET library already defines, so you don't need your own
delegatedeclaration for common shapes.
Lambda syntax
(a, b) => a + bis shorthand for a method takingaandb, and returninga + 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.