📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Observer pattern? Explain how C# events, IObservable<T>/IObserver<T> and IOptionsMonitor<T> change notifications implement it, how observers unsubscribe, and how Observer differs from publish/subscribe through a message broker.

Observer intent and structure, C# events and EventHandler<T>, IObservable<T>/IObserver<T> with IDisposable subscriptions and Rx, IOptionsMonitor<T>.OnChange and change tokens, INotifyPropertyChanged, unsubscribing and the leak risk, synchronous in-process notification vs broker-based pub/sub.

Junior Theory Intermediate design-patterns events iobservable ioptionsmonitor observer

🎯 Key points

  • Observer: a subject keeps a list of observers and notifies them when its state changes; the subject doesn't know their concrete types (one-to-many, loose coupling)
  • C# events are the built-in Observer: += subscribes, -= unsubscribes, the publisher raises with Event?.Invoke(this, args)
  • IObservable<T>.Subscribe returns an IDisposable; disposing it unsubscribes; IObserver<T> has OnNext, OnError and OnCompleted; Rx.NET adds LINQ-style operators
  • IOptionsMonitor<T>.OnChange returns an IDisposable? that must be disposed; it can fire more than once per file save, so listeners must be idempotent
  • Raising a C# event is synchronous and in-process: handlers run in subscription order on the raising thread, so a slow handler blocks the publisher
  • A throwing handler stops the remaining handlers and propagates to the publisher; catch inside handlers or iterate GetInvocationList() when isolation matters
  • The subject holds strong references to observers, so a long-lived subject with forgotten subscriptions leaks memory
  • Observer is in-process and tied to the subject's lifetime; pub/sub through a broker (Azure Service Bus) decouples in time and process and survives restarts

⏱ 30-second answer

Observer is a one-to-many relationship: a subject keeps a list of observers and notifies them when something happens, without knowing their concrete types.

In .NET it's built into the language:

  • C# events: += subscribes, -= unsubscribes, the publisher raises with Placed?.Invoke(this, e).
  • IObservable<T>/IObserver<T>: Subscribe returns an IDisposable; disposing it unsubscribes. Rx.NET adds LINQ-style operators over these streams.
  • IOptionsMonitor<T>.OnChange: notifies you when configuration reloads, and also returns an IDisposable you must dispose.

Notification is synchronous and in-process, and the subject holds strong references to its observers, so forgotten subscriptions on a long-lived subject leak memory. For cross-process, durable notification you use pub/sub through a broker instead.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Observer is when one object, the subject, needs to tell several others that something happened, without knowing who they are. The subject keeps a list of observers, observers register and unregister themselves, and when the subject's state changes it walks the list and calls each one. The point is loose coupling: the order service raises 'order placed' and doesn't need to know that loyalty points, email and analytics all care.

In C#, the language gives you this directly with events. An event EventHandler<OrderPlaced> is the observer list; += subscribes, -= unsubscribes, and the publisher raises it with Placed?.Invoke(this, e), where the null-conditional handles the case of no subscribers. There's also the IObservable<T> and IObserver<T> pair: Subscribe returns an IDisposable, and disposing it is how you unsubscribe. Observers get OnNext, OnError and OnCompleted, so it models a stream that can fail or finish. Rx.NET builds LINQ-style operators like Throttle and Buffer on top. In ASP.NET Core the one I use most is IOptionsMonitor<T>.OnChange: when appsettings.json or Azure App Configuration reloads, my callback runs with the new options. That also returns an IDisposable.

The mistake I see is forgetting that the subject holds a strong reference to every observer. If a short-lived object subscribes to a singleton's event and never unsubscribes, the singleton keeps it alive forever, which is the classic .NET event leak. The other thing to remember is that notification is synchronous: one slow or throwing handler blocks or breaks the publisher. Observer is great for in-process notifications, but every subscription is a reference you've promised to release."


Three ways .NET implements Observer

Mechanism Subscribe Unsubscribe Typical use
C# event subject.Placed += handler subject.Placed -= handler Domain or UI notifications in-process
IObservable<T> subject.Subscribe(observer) subscription.Dispose() Streams of values; Rx.NET pipelines
IOptionsMonitor<T> monitor.OnChange(callback) subscription?.Dispose() Config reload, feature flags

Others you'll meet: INotifyPropertyChanged (MVVM data binding), IChangeToken (configuration and file providers), CancellationToken.Register (notification on cancellation).

Observer vs publish/subscribe

Observer (events, IObservable) Pub/sub via a broker (Service Bus, Event Grid)
Where Same process Across processes and services
Coupling Observers reference the subject Publishers and subscribers only know the topic
Timing Synchronous, immediate Asynchronous; subscriber can be offline
Durability Lost if the process dies Messages persisted and retried
Failure A throwing handler affects the publisher Isolated per subscriber, with dead-lettering

Production example

A pricing service used IOptionsMonitor<PricingOptions>.OnChange to refresh a cached rate table when Azure App Configuration changed, so rate updates went live in under 30 seconds without a redeploy. A later code review found the subscription wasn't disposed in a scoped class created per request; after about [two days] the process held several hundred thousand callbacks. Moving the subscription into a singleton fixed it.

πŸ” What the interviewer is checking

Checks that the candidate recognises Observer in C# events and IObservable

Green flags

  • Explains +=/-= and IDisposable subscriptions.
  • Mentions IOptionsMonitor<T>.OnChange or change tokens.
  • Knows the subject holds strong references and how leaks happen.
  • Distinguishes in-process Observer from durable pub/sub.

Red flags

  • Thinks events are asynchronous or isolated from handler exceptions.
  • Never mentions unsubscribing.
  • Treats in-process events as reliable for critical side effects.

πŸ“š Learn in depth

1. Structure

          Β«subjectΒ»
        OrderBook
          observers: list
          Subscribe(o) / Unsubscribe(o)
          Notify() ── for each o: o.Update(e)
                β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β–Ό          β–Ό           β–Ό
 LoyaltyPoints  EmailSender  Analytics   (Β«observerΒ»s)

The subject depends only on the observer abstraction (a delegate type or IObserver<T>), which is why new observers can be added without changing it.

2. C# events under the hood

A field-like event EventHandler<T>? Placed; compiles to a private delegate field plus add and remove accessors that combine and remove delegates with a thread-safe compare-exchange loop. The delegate is multicast: its invocation list holds each handler (target object plus method). Raising it calls each handler in order, synchronously, on the raising thread. If one handler throws, the remaining handlers don't run and the exception propagates to the publisher. Placed?.Invoke(this, e) reads the field once, so a handler removed concurrently can't cause a NullReferenceException.

Since .NET Framework 4.5, EventHandler<TEventArgs> no longer requires TEventArgs : EventArgs, so a record works as the payload.

3. IObservable<T> and IObserver<T>

IObservable<T>.Subscribe(IObserver<T>) ──▢ IDisposable (the subscription)
IObserver<T>: OnNext(T) *  (OnError(Exception) | OnCompleted())?

The grammar is: any number of OnNext calls, then at most one terminal call. This is the push dual of IEnumerable<T> (pull). Writing a correct observable by hand is fiddly (thread safety, the grammar, disposal during notification), so in practice you use Rx.NET (System.Reactive) or Subject<T> from it, which also gives operators like Where, Throttle, Buffer and ObserveOn.

4. IOptionsMonitor<T> and change tokens

Configuration providers expose an IChangeToken. With reloadOnChange: true (the default for appsettings.json in WebApplication.CreateBuilder), a file watcher fires the token, configuration reloads, and IOptionsMonitor<T> recomputes the options and calls each OnChange listener with the new value and the options name. OnChange returns an IDisposable?; dispose it when the listener's owner goes away. File watchers can raise more than one event for a single save, so listeners should be idempotent.

5. Lifetimes and leaks

The subject holds a strong reference to each observer through the delegate's Target (or the observer list). If the subject lives longer than the observer, the observer can't be collected until it unsubscribes. Static events and singleton subjects are the usual culprits. Fixes: unsubscribe in Dispose, keep subscriptions in objects with the same lifetime as the subject, or use weak event patterns (WPF's WeakEventManager) where unsubscription can't be guaranteed.

6. Costs

  • Each subscription is a delegate allocation; raising an event is one indirect call per handler.
  • Synchronous handlers run on the publisher's thread: an async void handler escapes this, but its exceptions crash the process if unobserved.
  • Ordering between handlers is subscription order and shouldn't be relied on.

Try it yourself

  1. Write an OrderBook with an event and two subscribers; make one throw and observe that the second doesn't run.
  2. Implement IObservable<decimal> by hand, then replace it with Rx.NET's Subject<decimal> and add .Throttle.
  3. Subscribe to IOptionsMonitor<T>.OnChange, edit appsettings.json while the app runs, and count how many callbacks fire per save.
  4. Subscribe a short-lived object to a static event in a loop, take a dump with dotnet-gcdump, and find who keeps the objects alive.

πŸ’» Code

Three forms of Observer in .NET: a C# event, IObservable<T>, and IOptionsMonitor<T>.OnChange.

namespace Orders;

public sealed record OrderPlaced(Guid OrderId, decimal Total);

// 1. C# event: the language's built-in observer list
public sealed class OrderBook
{
    public event EventHandler<OrderPlaced>? Placed;

    public void Place(Guid id, decimal total)
    {
        // ... persist the order ...
        Placed?.Invoke(this, new OrderPlaced(id, total));   // reads the delegate once: safe with no subscribers
    }
}

public sealed class LoyaltyPoints : IDisposable
{
    private readonly OrderBook _book;

    public LoyaltyPoints(OrderBook book)
    {
        _book = book;
        _book.Placed += OnPlaced;          // the book now holds a reference to this object
    }

    private void OnPlaced(object? sender, OrderPlaced e) =>
        Console.WriteLine($"Award {(int)e.Total} points for {e.OrderId}");

    public void Dispose() => _book.Placed -= OnPlaced;   // release it, or a long-lived book keeps us alive
}
namespace Sensors;

// 2. IObservable<T>: subscription is an IDisposable. Not thread-safe; use Rx.NET's Subject<T> in real code.
public sealed class TemperatureSensor : IObservable<decimal>
{
    private readonly List<IObserver<decimal>> _observers = [];

    public IDisposable Subscribe(IObserver<decimal> observer)
    {
        _observers.Add(observer);
        return new Subscription(_observers, observer);
    }

    public void Publish(decimal reading)
    {
        foreach (var o in _observers.ToArray()) o.OnNext(reading);   // copy: observers may unsubscribe mid-loop
    }

    public void Complete()
    {
        foreach (var o in _observers.ToArray()) o.OnCompleted();
        _observers.Clear();
    }

    private sealed class Subscription(List<IObserver<decimal>> observers, IObserver<decimal> observer) : IDisposable
    {
        public void Dispose() => observers.Remove(observer);
    }
}
namespace Pricing;

using Microsoft.Extensions.Options;

public sealed class FeatureFlags { public bool NewCheckout { get; set; } }

// 3. IOptionsMonitor<T>.OnChange: register as a singleton so the subscription lives as long as the monitor
public sealed class FeatureFlagWatcher : IDisposable
{
    private readonly IDisposable? _subscription;

    public FeatureFlagWatcher(IOptionsMonitor<FeatureFlags> monitor, ILogger<FeatureFlagWatcher> logger)
    {
        _subscription = monitor.OnChange((flags, _) =>
            logger.LogInformation("Feature flags reloaded: NewCheckout={NewCheckout}", flags.NewCheckout));
    }

    public void Dispose() => _subscription?.Dispose();
}

// Program.cs
// builder.Services.Configure<FeatureFlags>(builder.Configuration.GetSection("FeatureFlags"));
// builder.Services.AddSingleton<FeatureFlagWatcher>();

⚠ Common mistakes

  • Mistake: Subscribing to a long-lived or static event and never unsubscribing. Why it is wrong: The publisher's delegate keeps the subscriber alive, so memory grows with every subscriber created. Instead: Unsubscribe in Dispose, or keep subscriptions in objects with the same lifetime as the publisher.
  • Mistake: Ignoring the IDisposable returned by Subscribe or IOptionsMonitor<T>.OnChange. Why it is wrong: The subscription is never removed, which leaks and keeps calling dead objects. Instead: Store it in a field and dispose it with the owner.
  • Mistake: Raising an event with if (Placed != null) Placed(this, e). Why it is wrong: The field is read twice, so a concurrent unsubscribe can cause a NullReferenceException. Instead: Placed?.Invoke(this, e).
  • Mistake: Doing slow I/O in a synchronous event handler. Why it is wrong: The publisher waits for every handler, so one slow observer slows the whole operation. Instead: Keep handlers fast, or hand work to a queue or Channel<T>.
  • Mistake: Assuming every handler runs even if one throws. Why it is wrong: The first exception stops the invocation list and propagates to the publisher. Instead: Catch inside handlers, or iterate GetInvocationList() with a try/catch per handler when isolation matters.
  • Mistake: Using in-process events for things that must survive a crash, such as sending a confirmation email. Why it is wrong: If the process dies after saving and before the handler runs, the notification is lost. Instead: Use a durable message (outbox plus a broker).
  • Mistake: Hand-writing IObservable<T> with a plain List<T> in multi-threaded code. Why it is wrong: Concurrent subscribe and publish corrupt the list or break the OnNext/OnCompleted grammar. Instead: Use Rx.NET's Subject<T> or a channel.

πŸ› Senior insight: trade-offs

Observer is cheap to add and easy to get wrong over time, because every subscription is an invisible reference and an invisible call on the publisher's thread. I keep events for genuinely in-process, best-effort notifications (UI updates, cache invalidation, config reload), and move anything that must not be lost to a durable message.

Option When it fits Cost When not to
C# event In-process, synchronous, few handlers Leaks if not unsubscribed; handler exceptions hit the publisher Work must survive a crash or run asynchronously
IObservable<T> + Rx.NET Streams needing throttling, buffering, composition Learning curve, extra package One-off notifications
IOptionsMonitor<T>.OnChange Reacting to config reload Callback may fire more than once per change Request-scoped classes (subscribe in singletons)
Channel<T> Decouple producer and slow consumers in-process Background consumer to manage Need durability across restarts
Broker pub/sub Cross-service, durable, independently scaled Infrastructure, eventual consistency Simple in-process notifications

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says C# events implement Observer Why: Checks what the event keyword generates and how to raise events safely
    How to answer

    An event is a delegate member with access restricted to subscribe and unsubscribe. Outside the class you can only use += and -=; only the owner can raise it or clear it, whereas a public delegate field can be invoked or overwritten by anyone. For a field-like event the compiler generates a private delegate field and thread-safe add and remove accessors. I raise it with Changed?.Invoke(this, e), which reads the field once. I avoid static events because they keep every subscriber alive until it unsubscribes.

  2. When: Candidate mentions that forgotten subscriptions leak memory Why: Checks diagnosing an observer lifetime leak in DI with dotnet-counters and dotnet-gcdump
    How to answer

    It's an Observer lifetime mismatch. The singleton PriceFeed holds every subscriber in its event's invocation list (a strong reference through each delegate's Target), so each request's PriceDisplayService stays reachable long after the request ends. The ignored IDisposable from IOptionsMonitor.OnChange does the same thing.

    To prove it: dotnet-counters shows GC heap and gen 2 size climbing without returning to baseline; two dotnet-gcdump snapshots show the PriceDisplayService count growing, with a path to root through PriceFeed β†’ EventHandler β†’ the service.

    The fix: unsubscribe in Dispose (the container disposes scoped services at the end of the request), dispose the OnChange token, or better, move the subscription into a singleton that caches the latest price. The trade-off is that per-request subscriptions are almost never what you want; align observer and subject lifetimes.

  3. When: Candidate uses EventHandler<T> or async handlers Why: Checks EventHandler conventions and async event handlers
    How to answer

    The convention is EventHandler<TEventArgs> with object? sender and an immutable args object, EventArgs.Empty when there is no data, and a protected virtual OnXxx method that raises it. The big production risk is leaks: the publisher's delegate holds a strong reference to every subscriber, so a singleton or static publisher keeps short-lived subscribers alive forever. I find them with a heap dump and gcroot, which shows the path through the event's delegate, and fix them by unsubscribing in Dispose or using a weak event. Async handlers are async void, so I keep them thin and catch everything inside.

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me