AdvancedLesson 14 of 16
Delegates, Lambdas & Events – C#
Pass functions as values and react to events.
A delegate is a type for method references. Most of the time you use the ready-made types Func<...> (with a return value), Action<...> (without) and Predicate<T> (returns bool). Lambdas (x => ...) create them inline.
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = msg => Console.WriteLine($"[LOG] {msg}");
Predicate<int> istGerade = x => x % 2 == 0;
log($"{add(2, 3)} {istGerade(4)}"); // [LOG] 5 True
new List<string> { "a", "b" }.ForEach(Console.WriteLine); // method groupEvents implement the observer pattern: one object reports something, any number of subscribers react. With ?.Invoke you raise them safely, even if nobody is listening.
var sensor = new Thermometer();
sensor.TemperaturGeaendert += t => Console.WriteLine($"New: {t} degrees");
sensor.Setze(21); // New: 21 degrees
sensor.Setze(25); // New: 25 degrees
class Thermometer
{
public event Action<int>? TemperaturGeaendert;
public void Setze(int temperatur)
{
TemperaturGeaendert?.Invoke(temperatur);
}
}Lambdas can "capture" variables from their surroundings (closure). Pay attention to the difference between for and foreach:
var aktionen = new List<Action>();
for (int i = 0; i < 3; i++)
aktionen.Add(() => Console.Write(i + " "));
foreach (var a in aktionen) a(); // 3 3 3
Console.WriteLine();
var aktionen2 = new List<Action>();
foreach (int j in new[] { 0, 1, 2 })
aktionen2.Add(() => Console.Write(j + " "));
foreach (var a in aktionen2) a(); // 0 1 2WarningIn the
for loop there is only one variable i that all lambdas share – after the loop it is 3. foreach, on the other hand, creates a new variable for each iteration. If you subscribe to events, you should also unsubscribe again (-=), otherwise the publisher keeps the subscriber alive.