You learn delegates, which carry methods around like variables, the ready-made Action and Func types, and how to publish and listen to events such as "temperature threshold exceeded" with event.
When the temperature sensor in a distribution panel goes above 60 degrees, several things should happen: an alarm should appear on screen, the event should be written to a log file, maybe a fan should start. Having the sensor class know about all of these one by one is bad design; the day you want to send an SMS, you have to change the sensor code. A better approach: the sensor only announces "threshold exceeded", and every interested part subscribes to that announcement on its own. In C# the tools for this are delegates and events. Every button click in Windows Forms works through the same mechanism.
Delegates: putting a method into a variable
A delegate is a type that can hold methods with a particular signature. You define a pattern such as "any method that takes a double and returns a double"; then you can assign any method that fits the pattern to a variable and call it.
Conversion convert = CelsiusToFahrenheit;
Console.WriteLine(convert(25));
convert = CelsiusToKelvin; // another method in the same variable
Console.WriteLine(convert(25));
static double CelsiusToFahrenheit(double c) => c * 9 / 5 + 32;
static double CelsiusToKelvin(double c) => c + 273.15;
delegate double Conversion(double value);
77
298.15
The line delegate double Conversion(double value); defines a new type; because it is a type declaration, we wrote it below the top-level code. We did not put parentheses when assigning the method: CelsiusToFahrenheit is the method itself, while CelsiusToFahrenheit(25) is the result of calling it. When you call the variable as convert(25), whichever method it holds at that moment runs.
Ready-made delegates: Func and Action
You do not have to define your own delegate type every time. .NET offers two ready-made generic families: Func<...> for methods that return a value (the last type parameter is the return type) and Action<...> for methods that return nothing. Func<double, double> means "take a double, return a double"; Action<string> means "take a string, return nothing". A method that takes a delegate parameter leaves part of its behaviour to the caller:
static void PrintTable(double[] values, Func<double, double> operation, Action<string> printer)
{
foreach (double d in values)
printer($"{d} -> {operation(d):F2}");
}
double[] temperatures = { 0, 25, 100 };
PrintTable(temperatures, c => c * 9 / 5 + 32, Console.WriteLine);
PrintTable(temperatures, c => c + 273.15, s => Console.WriteLine("K: " + s));
0 -> 32.00
25 -> 77.00
100 -> 212.00
K: 0 -> 273.15
K: 25 -> 298.15
K: 100 -> 373.15
Here is LINQ's secret: the Where method actually takes a parameter of type Func<T, bool>. The lambda you write as t => t > 22 is a small method handed to that delegate.
event: a sensor threshold event
An event is a delegate field with event in front of it. The class raises the event; outside code subscribes with +=. Several methods can subscribe to one event, and when it is raised they all run in order.
var sensor = new TemperatureSensor("Panel-1", threshold: 60);
sensor.ThresholdExceeded += Alarm;
sensor.ThresholdExceeded += value => Console.WriteLine($" [LOG] {value} C recorded");
foreach (double d in new[] { 45.0, 62.5, 58.0, 71.2 })
sensor.NewReading(d);
static void Alarm(double value) => Console.WriteLine($"ALARM! Temperature {value} C");
class TemperatureSensor
{
public string Name { get; }
public double Threshold { get; }
public event Action<double>? ThresholdExceeded;
public TemperatureSensor(string name, double threshold)
{
Name = name;
Threshold = threshold;
}
public void NewReading(double value)
{
Console.WriteLine($"{Name}: {value} C");
if (value > Threshold)
ThresholdExceeded?.Invoke(value);
}
}
Panel-1: 45 C
Panel-1: 62.5 C
ALARM! Temperature 62.5 C
[LOG] 62.5 C recorded
Panel-1: 58 C
Panel-1: 71.2 C
ALARM! Temperature 71.2 C
[LOG] 71.2 C recorded
The sensor class knows nothing about the alarm or the log. If you want to add fan control tomorrow, one line is enough: sensor.ThresholdExceeded += StartFan;. You do not touch the sensor's code. The ?. in ThresholdExceeded?.Invoke(value) matters: if there are no subscribers, the event is null, and calling it directly crashes the program.
The standard pattern: EventHandler and unsubscribing
Events in the .NET libraries usually use the EventHandler<T> type: the listener receives two things, who raised the event (sender) and the event data (a class derived from EventArgs). You unsubscribe with -=.
var panel = new Panel();
panel.CurrentChanged += Show;
panel.MeasureCurrent(12.5);
panel.CurrentChanged -= Show; // unsubscribe
panel.MeasureCurrent(14.0); // nobody is listening now
Console.WriteLine("Done");
static void Show(object? sender, CurrentEventArgs e) =>
Console.WriteLine($"New current: {e.Current} A");
class CurrentEventArgs : EventArgs
{
public double Current { get; }
public CurrentEventArgs(double current) => Current = current;
}
class Panel
{
public event EventHandler<CurrentEventArgs>? CurrentChanged;
public void MeasureCurrent(double current) => CurrentChanged?.Invoke(this, new CurrentEventArgs(current));
}
New current: 12.5 A
Done
The button1_Click(object sender, EventArgs e) method you get when you double-click a button in WinForms is exactly a listener of this pattern.
Common mistakes
- Raising an event without
?.:ThresholdExceeded(value);throws aNullReferenceExceptionwhen there are no subscribers. Always writeThresholdExceeded?.Invoke(value);. - Writing
=instead of+=: For events this is a compile error outside the class. For a plain delegate variable it compiles but wipes out all earlier methods; only the last one assigned remains. - Forgetting to unsubscribe, or trying to unsubscribe with a lambda: Short-lived objects subscribed to an event of a long-lived object stay in memory. Also,
-= x => ...does nothing; the newly written lambda is a different object. If you plan to unsubscribe, subscribe with a named method.
Exercise
Model an overcurrent relay. The OvercurrentRelay class takes a current limit and publishes an Action<double> event called Tripped. The Measure(double current) method trips the relay when the limit is exceeded and raises the event only once; while the relay is open, new readings are ignored. Reset() closes the relay again. With a 16 A limit, measure 8, 17, 18 and 9 A, then reset and measure 20 A. One subscriber prints to the screen, the second counts the trips.
Hint: Keep the relay state in bool IsOpen { get; private set; }. For the counting subscriber, a lambda that increments an outside int variable is enough; if you will not use the parameter, you can name it _.
Solution
var relay = new OvercurrentRelay(16);
int tripCount = 0;
relay.Tripped += current => Console.WriteLine($"TRIP! Current {current} A");
relay.Tripped += _ => tripCount++;
foreach (double a in new[] { 8.0, 17.0, 18.0, 9.0 })
relay.Measure(a);
relay.Reset();
relay.Measure(20);
Console.WriteLine($"Total trips: {tripCount}");
class OvercurrentRelay
{
public double Limit { get; }
public bool IsOpen { get; private set; }
public event Action<double>? Tripped;
public OvercurrentRelay(double limit) => Limit = limit;
public void Measure(double current)
{
if (IsOpen || current <= Limit) return;
IsOpen = true;
Tripped?.Invoke(current);
}
public void Reset() => IsOpen = false;
}
TRIP! Current 17 A
TRIP! Current 20 A
Total trips: 2
The 18 A reading did not create a new event because the relay was already open; a real protection relay does not send another trip signal until it is reset either.
You can now let parts communicate without tying them tightly together. In the next lesson we will learn short, safe record types for carrying data, and pattern matching.
// Spot the bug +10 XP
Exactly one line below is wrong. Click the faulty line.
Line 3 assigns to the event with =. Outside the class, only += and -= can be applied to a member declared as event, so the compiler reports an error. This rule stops one subscriber from accidentally removing all the others. Correct: sensor.ThresholdExceeded += d => Console.WriteLine($"Log: {d}");
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.


