When a customer confirms an order at the corner store, several things happen: the inventory goes down, a confirmation email goes out, a line is written to a log. Tomorrow someone will ask for a WhatsApp message too, or for the receipt to print at the counter. If the order has to know every one of those pieces, each new request forces you to open the Order class.
Observer solves that: the order says “I was confirmed” and whoever cares finds out, without the order knowing who they are.
The problem: the order knows everything
This is what you get when Order calls each interested party directly:
Order order = new Order("Ana", 23.00m);
order.Confirm();
class Order
{
public string Customer { get; private set; }
public decimal Total { get; private set; }
public Order(string customer, decimal total)
{
Customer = customer;
Total = total;
}
public void Confirm()
{
Console.WriteLine($"Order for {Customer} confirmed: {Total:0.00}");
Inventory inventory = new Inventory();
inventory.Deduct(Customer);
MailService mailer = new MailService();
mailer.SendConfirmation(Customer);
}
}
class Inventory
{
public void Deduct(string customer)
{
Console.WriteLine($"Inventory: deducting items for {customer}'s order");
}
}
class MailService
{
public void SendConfirmation(string customer)
{
Console.WriteLine($"Mail: confirmation sent to {customer}");
}
}
Order for Ana confirmed: 23.00
Inventory: deducting items for Ana's order
Mail: confirmation sent to Ana
It works, but Order depends on Inventory and on MailService. To add the log, WhatsApp or the receipt, you have to edit Confirm. And there is no way to test an order without sending emails, because the new MailService() is buried inside. This is the coupling we talked about in chapter 11.
Two new ideas: Action and lambdas
To solve this in C# you need to be able to store a method in a variable and call it later. The type that allows it is Action. An Action<string> stores any method that takes a string and returns nothing. You can call it as if it were the method:
Action<string> greet = Greeting;
greet("Ana");
Action<string> shout = name => Console.WriteLine($"HELLO, {name.ToUpper()}!");
Action<string> both = greet;
both += shout;
both("Luis");
static void Greeting(string name)
{
Console.WriteLine($"Hello, {name}");
}
Hello, Ana
Hello, Luis
HELLO, LUIS!
Three new things here:
Action<string> greet = Greeting;stores theGreetingmethod without running it. Notice there are no parentheses. Parentheses would be a call.greet("Ana")is what runs it.name => Console.WriteLine(...)is a lambda: a small function with no name. What is on the left of=>is the parameter and what is on the right is what it does. It is useful when the method is so short that naming it is not worth it.+=adds another method to the list. AnActioncan hold several, and when you call it they all run, in the order you added them. That is whyboth("Luis")printed two lines.
If you can store a list of methods and call them all at once, you already have a notification system.
event: the notification list with a lock
With that we could give Order a public Action<Order> and let every interested party add itself with +=. It works, but anyone outside could call it (order.Confirmed(otherOrder)) or replace it with = and wipe out every other subscriber. To prevent that, C# has the event keyword:
public event Action<Order>? Confirmed;
An event is an Action with a lock. From the outside you can only do two things: += to subscribe and -= to cancel. Only the owning class can fire the event. The ? after the type is there because, while nobody has subscribed, the event is null.
Here is the complete program, with Order announcing through an event:
Order order = new Order("Ana", 23.00m);
Inventory inventory = new Inventory();
MailService mailer = new MailService();
order.Confirmed += inventory.OnConfirmed;
order.Confirmed += mailer.OnConfirmed;
order.Confirmed += o => Console.WriteLine($"Log: order for {o.Customer} totaling {o.Total:0.00}");
order.Confirm();
Order second = new Order("Luis", 8.50m);
second.Confirmed += inventory.OnConfirmed;
second.Confirmed += mailer.OnConfirmed;
second.Confirmed -= mailer.OnConfirmed;
second.Confirm();
class Order
{
public string Customer { get; private set; }
public decimal Total { get; private set; }
public event Action<Order>? Confirmed;
public Order(string customer, decimal total)
{
Customer = customer;
Total = total;
}
public void Confirm()
{
Console.WriteLine($"Order for {Customer} confirmed: {Total:0.00}");
Confirmed?.Invoke(this);
}
}
class Inventory
{
public void OnConfirmed(Order order)
{
Console.WriteLine($"Inventory: deducting items for {order.Customer}'s order");
}
}
class MailService
{
public void OnConfirmed(Order order)
{
Console.WriteLine($"Mail: confirmation sent to {order.Customer}");
}
}
Order for Ana confirmed: 23.00
Inventory: deducting items for Ana's order
Mail: confirmation sent to Ana
Log: order for Ana totaling 23.00
Order for Luis confirmed: 8.50
Inventory: deducting items for Luis's order
Look at how Confirm changed. It no longer mentions Inventory or MailService. It only announces that the order was confirmed with Confirmed?.Invoke(this), and passes itself so each subscriber can read what it needs. The ?. means “call Invoke only if the event is not null”, that is, only if someone subscribed. Subscribers run in the order they subscribed, and the order does not know how many there are or what they do.
To add WhatsApp you write a class with its OnConfirmed method and one += line where you assemble the program. Order does not change.
Unsubscribing
Look at the second order: the mailer subscribes and is then removed with -=, so Luis gets only the inventory deduction. The -= has to receive the same method you passed to +=. That is why the log lambda, which has no name, cannot easily be removed: if you need to cancel one, store it first in an Action<Order> variable.
This matters more than it looks. The order keeps a reference to each subscriber, so while the order lives, subscribers cannot be freed from memory even if you no longer use them, and they keep receiving notifications you do not expect. In a short console program you will not notice. In one that runs for hours, with objects being created and discarded, a forgotten subscriber is a classic cause of odd behavior. The simple rule: if you subscribe to something that outlives you, unsubscribe when you are done.
The interface version
There is another way to do the same thing without event or Action, using what you already know from chapter 10. The order keeps a list of objects that satisfy an interface and loops over them:
Order order = new Order("Ana", 23.00m);
order.Subscribe(new Inventory());
order.Subscribe(new MailService());
order.Confirm();
interface IOrderObserver
{
void OnConfirmed(Order order);
}
class Order
{
private List<IOrderObserver> observers = new List<IOrderObserver>();
public string Customer { get; private set; }
public decimal Total { get; private set; }
public Order(string customer, decimal total)
{
Customer = customer;
Total = total;
}
public void Subscribe(IOrderObserver observer)
{
observers.Add(observer);
}
public void Confirm()
{
Console.WriteLine($"Order for {Customer} confirmed: {Total:0.00}");
foreach (IOrderObserver observer in observers)
{
observer.OnConfirmed(this);
}
}
}
class Inventory : IOrderObserver
{
public void OnConfirmed(Order order)
{
Console.WriteLine($"Inventory: deducting items for {order.Customer}'s order");
}
}
class MailService : IOrderObserver
{
public void OnConfirmed(Order order)
{
Console.WriteLine($"Mail: confirmation sent to {order.Customer}");
}
}
Order for Ana confirmed: 23.00
Inventory: deducting items for Ana's order
Mail: confirmation sent to Ana
It is the same pattern with different mechanics. The interface is more explicit: whoever subscribes has to be an object that implements IOrderObserver. With event, on the other hand, any method with the right shape can subscribe, even a one-line lambda. In C# the normal choice is event, because it comes with the list and the += and -= operators already built. The interface helps when each observer needs several methods (for example OnConfirmed and OnCancelled) or when you work in a language that has no events.
When NOT to use Observer
- There is only one interested party and it is always the same. Calling it directly is clearer. An event with a single subscriber is an indirection that buys nothing.
- Order matters. Subscribers run in subscription order, but depending on that is fragile. If “inventory first, then email” is a business rule, write it explicitly in one method.
- You need to know whether something failed. If a subscriber throws an exception, the ones after it do not run, and the code that fires the event receives an exception from a subscriber it does not know. With few subscribers and error handling in each one you can manage it; otherwise, prefer a direct call.
- The flow gets hard to follow. With events, reading
Confirmdoes not tell you what happens on confirmation. You have to look for the subscriptions. In a small program that is a cost you do not need to pay.
Mini-exercise: big order alert
Take the event program (the complete one, with Order, Inventory and MailService) and add a new subscriber that, if the order total is 20.00 or more, prints Big order: {customer}, {total}. If it is lower, it prints nothing. Do it with a lambda stored in an Action<Order> variable and subscribe it to both orders, Ana’s (23.00) and Luis’s (8.50).
For this solution we keep only Order, so the program stays short.
Suggested solution
Action<Order> alertBig = o =>
{
if (o.Total >= 20.00m)
{
Console.WriteLine($"Big order: {o.Customer}, {o.Total:0.00}");
}
};
Order ana = new Order("Ana", 23.00m);
ana.Confirmed += alertBig;
ana.Confirm();
Order luis = new Order("Luis", 8.50m);
luis.Confirmed += alertBig;
luis.Confirm();
class Order
{
public string Customer { get; private set; }
public decimal Total { get; private set; }
public event Action<Order>? Confirmed;
public Order(string customer, decimal total)
{
Customer = customer;
Total = total;
}
public void Confirm()
{
Console.WriteLine($"Order for {Customer} confirmed: {Total:0.00}");
Confirmed?.Invoke(this);
}
}
Order for Ana confirmed: 23.00
Big order: Ana, 23.00
Order for Luis confirmed: 8.50
The same lambda works for both orders and decides on its own when to act. Because alertBig lives in a variable, you could also cancel it with -=.
What you learned
- When one change has to notify several parts, having the object call them directly couples it to all of them.
Action<T>stores a method in a variable;+=adds methods to the list and calling it runs them all.- A lambda (
o => ...) is a short function with no name. eventis anActionwhere the outside can only do+=and-=; the owner fires it with?.Invoke.- Unsubscribe with
-=when the subscriber is done, especially if the publisher lives longer. - The interface version (
IOrderObserver) is the same pattern and helps when an observer needs several methods.
In the next chapter we cover Singleton: the pattern that gets misused the most, and why you have to be careful with it.
Stuck?
If the event does not fire or you do not see why a subscriber does not run, DM me on Instagram or ask in the Discord community. Paste your code and the error you get, and we will look at it together.
