Module 1 · Foundations: Patterns, SOLID and Judgment · Lesson 2 of 20
SOLID in Modern C#: The Five Principles as the Foundation for Every Pattern, With a Real Refactor
Add a discount without rewriting checkout
On a subtotal of 200, a Gold customer should pay 180, a Staff customer 140, and a regular customer 200. Now the business wants a Platinum rate. Before changing anything, pin down those three totals so you know the old rules still work.
Separate the discount rule from saving the order and sending the notification. In the refactor below, checkout still runs those steps in order. Add a Platinum rule and register it where the service is assembled, rather than editing the checkout flow. That is the Open/Closed Principle: extend the behavior at a deliberate change point. Check rule order if more than one rule can match.
Learn the design decisions first
SOLID gives five checks for keeping the cost of change manageable. Each principle helps examine one design decision:
- Single Responsibility: how many reasons does this class have to change?
- Open/Closed: can I add a variant without editing working code?
- Liskov Substitution: can every implementation be used wherever its abstraction is expected, without surprises?
- Interface Segregation: does each client depend only on what it uses?
- Dependency Inversion: does the policy depend on abstractions that it owns, rather than on infrastructure details?
Most design patterns are concrete recipes for one or more of these principles. If you understand SOLID, patterns stop being a list to memorise.
Worked example: price an order, then follow its effects
The coordinating service saves the priced order and then notifies. Separating these responsibilities makes the choices replaceable, while the save/notify sequence still needs its own failure policy.
| Fixture / boundary | Result or obligation | Question to defend |
|---|---|---|
| Gold / staff / regular at 200 | 180 / 140 / 200 | Which policy varies independently? |
| Three successful checkouts | 3 saves and 3 notifications | Which ports describe the caller’s needs? |
| Save succeeds, notify throws | Earlier save may already have happened | How is reliable notification intent recorded? |
| Read-only IList.Add | NotSupportedException is documented | Does the caller require mutation or only reading? |
Reading map: Follow the chosen discount into checkout, then the save and notification calls in order. Keep the separate IList mutation example tied to its documented read-only capability.
Before: the problem in code
One method validates, prices, stores and notifies. Under the stated actor/change assumptions it mixes responsibilities, requires editing pricing for a new customer tier, and hard-wires file/console I/O into policy. Such code can still be tested with controlled side effects, but isolated policy tests are harder. The console line is a notification stand-in, not an actual SMTP send.
The output below comes from a run with a dot-decimal culture and no existing orders.csv in the working directory. File.AppendAllText adds rows to that file. Running the example again in the same directory keeps the earlier rows, so the final file read will print more rows.
namespace Before;
// One class that validates, prices, saves and emails. Every new rule edits this file.
public sealed class OrderService
{
public decimal PlaceOrder(string customerType, decimal subtotal, string email)
{
if (subtotal <= 0) throw new ArgumentOutOfRangeException(nameof(subtotal));
decimal discount;
if (customerType == "gold") discount = subtotal * 0.10m;
else if (customerType == "staff") discount = subtotal * 0.30m;
else discount = 0m; // a new tier means editing this method (OCP)
var total = subtotal - discount;
File.AppendAllText("orders.csv", $"{email},{total}\n"); // hard-wired storage (DIP)
Console.WriteLine($"SMTP to {email}: total {total}"); // hard-wired notification (SRP)
return total;
}
}
public static class Demo
{
public static void Main()
{
var service = new OrderService();
service.PlaceOrder("gold", 200m, "a@x.test");
service.PlaceOrder("staff", 200m, "b@x.test");
service.PlaceOrder("regular", 200m, "c@x.test");
Console.Write(File.ReadAllText("orders.csv"));
}
}SMTP to a@x.test: total 180.00 SMTP to b@x.test: total 140.00 SMTP to c@x.test: total 200 a@x.test,180.00 b@x.test,140.00 c@x.test,200
Code example
The refactor separates pricing rules, storage and notification from the coordinating policy. For a new project, run the following block as Program.cs in a .NET 10 LTS console project with SDK implicit usings enabled. The original sample used .NET 8 and C# 12. .NET 8 reached the end of support on 10 November 2026. The earlier Before block is separate illustrative code. If you include it, put it in its own file so its file-scoped namespace stays separate from this top-level program.
The fixture supplies non-null inputs and trusted rules. First matching rule wins in supplied order; no match means zero discount. Define overlap/priority and a valid-discount contract (for this example, 0 through subtotal) before extending it, and validate untrusted implementations/inputs as appropriate. This small synchronous in-memory demonstration does not provide persistent storage, concurrency safety, transactionality across save/notify or exactly-once delivery.
In the refactor, checkout receives three roles through interfaces. The discount rule chooses the amount to subtract. The repository saves the priced order, and the notifier records that it was placed.
flowchart LR
checkout["Checkout"] --> pricing["Discount rule"]
checkout --> storage["Order storage"]
checkout --> notification["Notification"]
These arrows show checkout's dependencies. The method uses them to price the order, save it and then notify, in that order.
// SOLID refactor of Before.OrderService: each reason to change gets its own type,
// and the high-level policy depends only on abstractions.
var repo = new InMemoryOrderRepository();
var notifier = new RecordingNotifier();
var service = new OrderService(
[new GoldDiscount(), new StaffDiscount()], // OCP: add a tier by adding a class
repo, notifier);
Console.WriteLine($"{service.PlaceOrder(new Order("a@x.test", "gold", 200m)):0.00}");
Console.WriteLine($"{service.PlaceOrder(new Order("b@x.test", "staff", 200m)):0.00}");
Console.WriteLine($"{service.PlaceOrder(new Order("c@x.test", "regular", 200m)):0.00}");
Console.WriteLine($"saved={repo.Count} notified={notifier.Sent.Count}");
// IList<T> permits read-only implementations; callers must not assume Add is supported.
IList<int> list = new List<int> { 1, 2 }.AsReadOnly();
try { list.Add(3); }
catch (NotSupportedException) { Console.WriteLine("LSP: ReadOnlyCollection<T> as IList<T> throws on Add"); }
IReadOnlyList<int> honest = [1, 2];
Console.WriteLine($"ISP: IReadOnlyList<int> exposes no Add; Count={honest.Count}");
public sealed record Order(string Email, string CustomerType, decimal Subtotal);
// ISP: small, role-specific interfaces.
public interface IDiscountRule { bool AppliesTo(Order o); decimal Discount(Order o); }
public interface IOrderRepository { void Save(Order o, decimal total); }
public interface IOrderNotifier { void OrderPlaced(Order o, decimal total); }
public sealed class GoldDiscount : IDiscountRule
{
public bool AppliesTo(Order o) => o.CustomerType == "gold";
public decimal Discount(Order o) => o.Subtotal * 0.10m;
}
public sealed class StaffDiscount : IDiscountRule
{
public bool AppliesTo(Order o) => o.CustomerType == "staff";
public decimal Discount(Order o) => o.Subtotal * 0.30m;
}
// SRP: OrderService only coordinates; DIP: it receives abstractions.
public sealed class OrderService(IEnumerable<IDiscountRule> rules, IOrderRepository repo, IOrderNotifier notifier)
{
private readonly IReadOnlyList<IDiscountRule> _rules = rules.ToList();
public decimal PlaceOrder(Order order)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(order.Subtotal);
var discount = _rules.FirstOrDefault(r => r.AppliesTo(order))?.Discount(order) ?? 0m;
var total = order.Subtotal - discount;
repo.Save(order, total);
notifier.OrderPlaced(order, total);
return total;
}
}
public sealed class InMemoryOrderRepository : IOrderRepository
{
private readonly List<(Order, decimal)> _rows = [];
public int Count => _rows.Count;
public void Save(Order o, decimal total) => _rows.Add((o, total));
}
public sealed class RecordingNotifier : IOrderNotifier
{
public List<string> Sent { get; } = [];
public void OrderPlaced(Order o, decimal total) => Sent.Add($"{o.Email}:{total}");
}180.00 140.00 200.00 saved=3 notified=3 LSP: ReadOnlyCollection<T> as IList<T> throws on Add ISP: IReadOnlyList<int> exposes no Add; Count=2
Sample output (.NET 8, Release, dot-decimal culture)
The output panel above keeps the original .NET 8 sample result. The unchanged program also produced these lines on .NET 10. The decimal separator follows the current culture.
Code walkthrough
GoldDiscounttakes 10% of 200, so the first order totals 180.00;StaffDiscounttakes 30%, giving 140.00; the regular customer matches no rule and pays 200.00.- Adding a compatible "platinum" rule is a new
IDiscountRuleclass plus registration/composition.OrderServiceneed not change for this anticipated variation; registration and any ordering policy still change. OCP is not a promise that all future business changes require no edits. InMemoryOrderRepositoryandRecordingNotifierreplace the file write and console-notification stand-in. Three rows and three notification records are collected without disk/network I/O; no actual email is sent. If a real notifier fails after save, the order may already be persisted. Interfaces alone do not solve this failure window. Use appropriate transaction/outbox and idempotency design where required.- The LSP demo calls
Addthrough anIList<int>that is really aReadOnlyCollection<int>and getsNotSupportedException.IReadOnlyList<int>has noAddthrough that interface; itsCountis 2. That is interface segregation, not a guarantee that all aliases/elements are immutable. Numeric0.00formatting follows current culture, which is why the sample names a dot-decimal culture.
Check the boundary
Suppose the refactored checkout’s save completes, then its notifier throws. What can you conclude from the displayed SOLID structure alone?
Show answer
Correct answer: D
Separating responsibilities and depending on ports improves substitution and testing. It does not couple external effects into a transaction. If durable notification is required, record intent with the business update and design dispatch/retry/idempotency explicitly.
Hint: Trace the call order and look for an actual commit/rollback boundary.
Design choices and limits
- Single Responsibility (SRP). Robert C. Martin's wording is "a module should be responsible to one, and only one, actor". It is about reasons to change, not about "doing one thing". Pricing rules change when marketing asks; storage changes when the DBA asks; notifications change when the product team asks. One class serving three actors gets three kinds of change requests and three kinds of merge conflicts.
- Open/Closed (OCP). "Open for extension, closed for modification." In C# this usually means: the code that varies sits behind an interface, and new behaviour arrives as a new class registered in DI. Do not over-apply it: you cannot make code closed against every change, only against the kinds of change you predict or have already seen.
- Liskov Substitution (LSP). A subtype must honour the contract of its base type: preconditions cannot be strengthened, postconditions cannot be weakened, invariants must hold, and permitted failure behavior must remain within the abstraction's contract. LSP is about semantic guarantees, not an absolute ban on exceptions. The BCL has a capability-based contract:
ReadOnlyCollection<T>implementsIList<T>, reportsIsReadOnly, and throws the documentedNotSupportedExceptionfromAdd. This is not a violation of that documented contract; callers cannot assume everyIList<T>is writable. For a client that only reads, prefer the narrowerIReadOnlyList<T>(added in .NET Framework 4.5). This removes mutating members from that interface, not all ways to mutate the underlying object: another alias or mutable element may still change it. Read-only access is not deep immutability or a security boundary. - Interface Segregation (ISP). Clients should not be forced to depend on methods they do not use. Prefer
IOrderReaderandIOrderWriter(or one interface per use case) over a 30-methodIOrderRepository. In the BCL,IReadOnlyCollection<T>,IReadOnlyList<T>andIReadOnlyDictionary<TKey,TValue>are examples of segregated interfaces. - Dependency Inversion (DIP). "High-level modules should not depend on low-level modules; both should depend on abstractions." The important detail is that the abstraction expresses policy needs rather than forcing policy to know infrastructure details. An application-owned
IOrderNotifiercan express the ordering use case while an SMTP adapter implements it. Stable shared/framework abstractions can also be appropriate; every interface need not physically live in the domain assembly. Merely copying vendor-specific types and operations into an interface may preserve the unwanted coupling rather than invert it. - DIP is not DI. Dependency Injection is a technique (pass dependencies in, usually via the constructor). Inversion of Control is the broader idea (a framework calls you). Dependency Inversion is a design principle about the direction of source-code dependencies. You can do DI and still violate DIP.
- Modern C# helps:
- primary constructors (C# 12) remove constructor-injection boilerplate;
- records provide generated value-based equality for messages and DTOs, but do not make referenced objects deeply immutable;
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(.NET 8) keeps guard clauses short;- collection expressions (
[a, b]) keep composition roots readable.
Real-world .NET usage
- ASP.NET Core is built on DIP: your controllers depend on
ILogger<T>,IOptions<T>and your own interfaces; the host wires concrete types at startup. - Unkeyed
IEnumerable<IDiscountRule>injection supplies the registered unkeyed implementations in registration order; ASP.NET Core uses this collection-resolution idea for startup filters and authorization handlers. Health checks instead useHealthCheckServiceOptions.Registrationsand registration factories, not simply an injectedIEnumerable<IHealthCheck>. Keyed services require an explicit keyed-resolution policy. - Minimal APIs and vertical-slice architectures apply SRP per use case: one handler per request rather than one service per entity.
Trade-offs
| Principle | Over-applied looks like | Healthy middle ground |
|---|---|---|
| SRP | One class per method, impossible to navigate | One class per actor or use case |
| OCP | Plugin architecture for code that never varies | Interfaces where variation is real or already happened twice |
| LSP | Deep inheritance trees with overrides that throw | Prefer composition; narrow interfaces |
| ISP | Dozens of one-method interfaces | Interfaces shaped by what each client calls |
| DIP | An interface for every class, including DTOs | Abstractions at boundaries (I/O, time, external services) |
Failure modes
- Interfaces that mirror the implementation one-to-one (
IOrderServicewith every public method ofOrderService), created only by habit. - "SRP" interpreted as "one method per class", which multiplies types without reducing coupling.
- An override that throws instead of providing an operation the base contract guarantees can violate LSP; a documented unsupported capability is different. The compiler does not prove semantic substitutability.
- Depending on
DateTime.Now,File,HttpClientor static singletons inside business logic, so tests become slow or flaky. InjectTimeProvider(.NET 8) for time. - A repository returning
IQueryable<T>exposes query-provider capabilities, deferred execution and lifetime concerns to callers. That may be intentional, but is not a provider-neutral persistence boundary just because it is an interface.
Interview angle
A strong answer to "Explain SOLID" gives one sentence per principle and one concrete C# example, then shows judgment: "I apply OCP where change is predictable, like discount rules; I do not wrap a DTO in an interface." Expect follow-ups:
- "Does an unsupported operation necessarily violate LSP?" → No.
IList<T>permits read-only implementations andStreampermitsCanSeek == false; the documented capability checks and exceptions are part of their contracts. A violation would break a guarantee the abstraction actually makes. - "What is the difference between DIP and DI?" → principle about dependency direction versus a technique for supplying dependencies.
- "Can you over-apply SOLID?" → yes; show the trade-off table above.
Practise the decision
Attempt before comparing
- What does "one reason to change" mean in practice?
- How does the Strategy pattern relate to the Open/Closed Principle?
- Why is
Square : Rectangle(with settable width and height) an LSP violation?
- Who should own the interface in Dependency Inversion?
- Your team wraps every class in an interface. Is that DIP?
- How would you make code that uses
DateTime.UtcNowtestable in .NET 8?
Hint if needed
List reasons to change, allowed operations and failure boundaries independently. A better dependency graph is not a transaction.
Compare the reasoning
- Answer: One actor or stakeholder group whose requests change the class. If marketing changes discount rules and operations changes storage, those belong in different classes so their changes do not collide.
- Answer: Strategy places an anticipated variation behind a stable contract. A compatible new variant can leave the context unchanged while composition/registration selects it. Changed contracts or policy requirements can still require edits; adding an interface does not automatically satisfy OCP.
- Answer: Callers of
Rectangleexpect width and height to vary independently (setting width keeps height). ASquaremust change both, so code that is correct forRectanglebreaks forSquare. Model them as separate immutable types or as records without inheritance.
- Answer: Shape the abstraction around high-level policy needs; application/domain-owned ports with infrastructure adapters are a common way to make dependencies point inward. A stable shared contract can also work. An interface that leaks vendor-specific requirements does not automatically achieve DIP.
- Answer: Not necessarily. DIP is about depending on abstractions at volatile boundaries. Interfaces for stable, dependency-free classes add indirection without benefit; mocks of them also make tests fragile.
- Answer: Inject
TimeProviderand callGetUtcNow(). Production registersTimeProvider.System; tests use a fake (for exampleFakeTimeProviderfromMicrosoft.Extensions.TimeProvider.Testing) and advance time explicitly.
Related on TechInterviewNotes
Lookup
SOLID smells and fixes
- Method with many
if (type == ...)branches → Strategy (OCP). - Class edited by three teams → split by actor (SRP).
- Override rejects a promised operation → inspect the contract; narrow capabilities or compose when appropriate. Documented optional operations are not automatically LSP violations.
new SqlConnection(...)in business logic → inject an abstraction the domain owns (DIP).DateTime.UtcNowin logic →TimeProvider.
Practice
TechInterviewNotes Editorial Team · Updated 24 Nov 2026 ·