What is the Observer pattern, and how does C# support it?
Quick Answer
Observer defines a one-to-many dependency: when a subject changes state, all its registered observers are notified automatically. In C# this is built in via events and delegates (publisher.OrderPlaced += handler), and the IObservable<T>/IObserver<T> interfaces / Reactive Extensions for stream-based scenarios.
Observer is one subject, many observers: the subject changes, and everyone who registered gets notified. C# has this baked in as events — the publisher declares an event, subscribers do += handler, and the publisher raises it. The gotcha is you have to unsubscribe with -= or the publisher keeps the subscriber alive and you leak memory. At the application level, domain events or MediatR notifications are the same pattern — “order placed” fires, and separate handlers send the email, update inventory and write the audit log without the order code knowing about any of them.
- Events: the subject exposes an
event; observers subscribe with+=and unsubscribe with-=(forgetting the-=is a common memory leak). - In-process domain events / MediatR notifications are an observer-style pattern for decoupling “when X happens, also do Y and Z”.
IObservable<T>+ Rx for push streams (UI events, sensor data) with operators like throttle, buffer, merge.