intermediate · 27 minute study
Functions can be values, and subscriptions have lifetimes
Understand callbacks, notifications and event-related memory leaks before building a reactive UI or game system.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- Generics keep a relationship intact across a reusable algorithm — Write one list helper that preserves element types, and select collection structures that match how you access the data.
First, build a mental model
A delegate is a typed callable value. An event lets outside code subscribe to a notification while the publisher controls when that event is raised.
- Action<int> describes a callable taking int and returning void; Func<int,int> describes a callable returning int.
- A lambda can capture surrounding variables. The captured objects may stay reachable for as long as the delegate does.
- Subscribers use += and -=. To remove a subscription, retain the delegate instance or use the same target/method pairing.
- Ordinary delegate invocation is synchronous; a publisher needs an explicit error policy if a subscriber can throw.
var counter = new ScoreCounter();
Action<int> show = value => Console.WriteLine(value);
counter.Changed += show;
counter.Add(5);
counter.Changed -= show;
counter.Add(2);
sealed class ScoreCounter
{
public int Score { get; private set; }
public event Action<int>? Changed;
public void Add(int delta)
{
Score += delta;
Changed?.Invoke(Score);
}
}- Subscribe
show becomes a listener for Changed.
- First update
The counter reaches 5 and invokes the listener, printing 5.
- Unsubscribe
The counter later reaches 7, but show is no longer invoked.
Production thinking
Take this beyond the example.
Document who publishes, who subscribes, whether handlers may throw and how subscriptions end. Prefer explicit lifecycle ownership over hidden global event buses.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · A LINQ query can be a recipe rather than a snapshot →