Roadmap › C# Language — Basics to Advanced › Module: Methods and Functional C#
Lessons in this course (38)
22. Delegates, Func, Action, events and lambdas
Intermediate★ Must knowLesson 22 of 38
A delegate is a type-safe reference to a method. Func<..., TResult> returns a value, Action<...> returns void, Predicate<T> returns bool.
csharp
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = msg => Console.WriteLine(msg);
Predicate<int> isEven = n => n % 2 == 0;
public class Thermostat
{
public event EventHandler<double>? TooHot; // event = delegate with restricted access
public void Read(double t) { if (t > 40) TooHot?.Invoke(this, t); }
}
var th = new Thermostat();
th.TooHot += (s, t) => Console.WriteLine($"Alert {t}");
th.Read(45);- Event vs delegate: outside the class, an event can only be subscribed (
+=) or unsubscribed (-=); it cannot be invoked or reassigned. - Multicast: a delegate can hold several methods; all are invoked in order.
- Closure: a lambda captures variables from the outer scope (by reference, not by value).