Roadmap › Design Patterns (GoF + Enterprise) in C# › Module: Behavioural Patterns
Lessons in this course (18)

11. Observer and events

Intermediate★ Must knowLesson 11 of 18

Subjects notify subscribed observers when state changes. In C#: events/delegates, IObservable<T>/IObserver<T>, Rx, and at system level message brokers (pub/sub).

csharp
public class StockTicker
{
    public event EventHandler<PriceChanged>? PriceChanged;
    public void Update(string sym, decimal price) => PriceChanged?.Invoke(this, new PriceChanged(sym, price));
}
var ticker = new StockTicker();
ticker.PriceChanged += (_, e) => Console.WriteLine($"{e.Symbol}: {e.Price}");

Remember to unsubscribe (-=) — a long-lived publisher holding handlers of short-lived subscribers is a classic memory leak.