LLearnCode
Academy/csharp/Collections and behavior

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.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

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.

  1. Action<int> describes a callable taking int and returning void; Func<int,int> describes a callable returning int.
  2. A lambda can capture surrounding variables. The captured objects may stay reachable for as long as the delegate does.
  3. Subscribers use += and -=. To remove a subscription, retain the delegate instance or use the same target/method pairing.
  4. Ordinary delegate invocation is synchronous; a publisher needs an explicit error policy if a subscriber can throw.
Read the codecsharp · educational example
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);
    }
}
  1. Subscribe

    show becomes a listener for Changed.

  2. First update

    The counter reaches 5 and invokes the listener, printing 5.

  3. 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 →