SOLID & Design Patterns Interview Question #36

What is the difference between the Observer Pattern and C# events?

Structural, Creational & Behavioral Patterns Junior Beginner

Quick Interview Answer

Observer is the design concept: a publisher notifies interested subscribers about changes. C# events are a language mechanism that can implement that concept using delegates and controlled subscription.

Detailed Explanation

Observer is the design concept: a publisher notifies interested subscribers about changes. C# events are a language mechanism that can implement that concept using delegates and controlled subscription.

Observer can also be implemented with interfaces, reactive streams, message brokers, or other mechanisms. Therefore an event-based implementation is one form of Observer, not the definition of the pattern itself.

Code Example

orderService.OrderCreated += OnOrderCreated;

void OnOrderCreated(object? sender, Order order)
{
    Console.WriteLine($"Created: {order.Id}");
}