⚙️ C# / .NET Intermediate

What is the Observer pattern and how is it implemented in C#?

Answer

The Observer pattern defines a one-to-many dependency — when one object (subject/observable) changes state, all its dependents (observers) are automatically notified. In C#, implemented via: (1) Events and delegates: the most idiomatic C# implementation — the subject exposes an event; observers subscribe with event handlers. button.Clicked += OnClicked;. (2) IObservable<T> / IObserver<T>: .NET's formal observer interfaces, forming the basis of Reactive Extensions (Rx.NET). IObservable<T> represents a push-based sequence; observers subscribe and receive OnNext, OnError, OnCompleted callbacks. (3) Reactive Extensions (Rx.NET): powerful library for composing asynchronous event streams with LINQ-style operators. Used in UI frameworks, real-time data processing. The observer pattern is fundamental for decoupled event-driven architectures.