Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 182 ยท Classes and Objects

Designing with Objects: SOLID in C#

Learn the SOLID principles in C# with small runnable examples - single responsibility, open/closed, Liskov substitution, interface segregation, dependency inversion, plus composition and immutability.

Knowing the syntax of classes, interfaces and records is one skill. Knowing how to arrange them so a program stays easy to change is another. Most software lives for years, and the cost of a design shows up when a new requirement arrives: does it mean adding a small class, or rewriting five existing ones and hoping nothing breaks?

The SOLID principles are five guidelines from object-oriented design that help with this. They are not laws, and applying them everywhere produces over-engineered code, but they give you a vocabulary for design smells you will meet in every codebase. This lesson explains each one in plain words, shows a "before" that hurts and an "after" that does not, using small runnable C# examples, and ends with two companions that matter just as much in modern C#: composition over inheritance and immutability. It builds on inheritance, abstract classes and interfaces and polymorphism.

S: Single Responsibility Principle

A class should have one reason to change.

"Responsibility" means a reason to change tied to one actor or concern: pricing rules, file formats, user-interface text. A class that mixes several of them breaks when any of them changes, and every change risks the others.

Here is an Invoice that calculates totals, formats a text report and also decides where to store itself:

C# Before: one class, three reasons to change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If the tax rate changes, if the report needs HTML, or if storage moves to a database, this one class is edited. Split by reason to change:

C# After: each class has one job

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output is the same, but a change to the tax rule now touches TaxCalculator only, and HTML output means a new printer class. Do not go overboard: a class with three tiny methods that all change together is cohesive, not a violation. Split when you notice different reasons to change, not by counting methods.

O: Open/Closed Principle

Software entities should be open for extension but closed for modification.

You want to add new behaviour by adding new code, not by editing code that already works and is already tested. The usual smell is a growing switch or if/else chain over a "type" value.

C# Before: a switch that grows with every new shape (compiles, but fragile)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Move the varying behaviour behind an abstraction. New shapes become new classes; the code that uses shapes never changes:

C# After: extend by adding a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Adding Triangle required no edits to TotalArea or to the other shapes. This is polymorphism put to work. Caveat: a switch over a closed set of cases, especially with pattern matching and a sealed hierarchy, is sometimes the better design (adding an operation is easy, and the compiler warns about missing cases). Choose based on what is more likely to change: new types (use polymorphism) or new operations (use a switch).

L: Liskov Substitution Principle

Code that works with a base type must keep working with any subtype.

A subclass must honour the contract of its base: it can accept at least what the base accepted and promise at least what the base promised. The classic violation is a Square that inherits from Rectangle. Mathematically a square is a rectangle, but in code the base class promises that width and height change independently.

C# A subtype that breaks the base contract

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The loop is correct for Rectangle and wrong for Square: the square reports 4 (2 x 2) instead of 10. Any code with a Rectangle parameter now needs if (r is Square), which defeats the point of inheritance. The fix is to model what really varies, here with an immutable shared abstraction instead of mutable setters:

C#
interface IShape { double Area { get; } }
record Rectangle(double Width, double Height) : IShape { public double Area => Width * Height; }
record Square(double Side) : IShape { public double Area => Side * Side; }

Signs of an LSP violation to watch for: an override that throws NotSupportedException, an override that does nothing, an override that adds stricter requirements on arguments or weakens results, and type checks on the base type in client code. The principle is the reason for the advice "inherit for is-a behaviour, not for reuse".

I: Interface Segregation Principle

Clients should not be forced to depend on methods they do not use.

Fat interfaces force implementers to write members they cannot support, and callers to know about operations they do not need.

C# Before: a fat interface (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The program prints printing report and then ends with Unhandled exception. System.NotSupportedException: this printer cannot scan. The type system promised a scanner, and reality did not deliver it (which is also an LSP violation). Split the interface into small role interfaces. A class implements only those it supports, and a class needing everything composes them:

C# After: small role interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You see this in .NET itself: IEnumerable<T>, ICollection<T> and IList<T> grow in layers so that a method needing only to read a sequence can ask for just IEnumerable<T> (see collection interfaces).

D: Dependency Inversion Principle

High-level code should depend on abstractions, not on concrete low-level details.

If your order-processing logic creates a SmtpClient directly, it can only ever send real email, and every test sends real email. Invert the dependency: the high-level class declares what it needs as an interface, and the caller provides an implementation (this is called dependency injection, and the whole dependency injection chapter builds on it).

C# Depend on an abstraction and inject it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

OrderService has no idea how notification works. Swapping email for SMS or a fake means writing a class, not editing the service. Note the direction: before, the high-level service pointed at a low-level detail; now both point at the INotifier abstraction, which the service's needs define. Keep it proportionate: do not create an interface for every class. Introduce one where there is a real seam, such as I/O, time, randomness, networks or several genuine implementations.

Composition over inheritance

Inheritance is the tightest coupling in C#: a subclass depends on the internals of its base, and only one base class is allowed. Composition means building behaviour by holding other objects and delegating to them. It is more flexible, because the parts can be swapped at runtime, and it avoids deep hierarchies.

C# Behaviour by composition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Shipping rules are small objects combined like building blocks (FreeOver wraps any other rule). With inheritance you would need classes such as FreeOverPerKiloDelivery, and a new combination would mean a new subclass. Use inheritance for a genuine, stable is-a relationship with a real shared contract; use composition for "has-a" and "uses-a", which covers most cases.

Immutability

An object that cannot change after construction is easier to reason about: no hidden state changes, no surprises when shared between callers or threads, safe as a dictionary key, and trivially cacheable. Modern C# makes this cheap: init properties, readonly fields, records with with, and ImmutableList<T>-style collections (immutable collections).

C# Records and with-expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

MoveTo returns a new customer instead of changing the old one, so any code still holding customer sees consistent data. The practical rule: make types immutable by default and allow mutation where it is the point (a builder, a performance-critical buffer, a long-lived entity with an identity). If you make a type mutable, keep its mutable state private and expose operations that keep it valid (see access modifiers).

A word of balance

SOLID is a means, not a goal. A 30-line script does not need five interfaces. Apply a principle when you feel the pain it addresses: a class that changes for unrelated reasons (S), a switch you edit for every feature (O), an override that cannot honour its base (L), an interface members nobody can implement (I), or code you cannot test without the real world (D). Often the simplest fix is also the best: a small class, a function, a record.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Report class calculates numbers, formats HTML and writes files. Which principle does it most clearly violate?

    It has several unrelated reasons to change: calculation rules, presentation and storage.
  2. 2. Which technique lets you add a new shape without editing the code that sums areas?

    That is the open/closed principle: new behaviour arrives as new code behind an abstraction, and client code stays unchanged.
  3. 3. Why is Square : Rectangle with overridden setters a Liskov violation?

    The subtype changes the behaviour that clients of the base type rely on, so it cannot be substituted safely.
  4. 4. What does the Dependency Inversion Principle recommend for a service that must send notifications?

    The service depends on an interface that describes what it needs, and the caller provides the implementation (or a fake in tests).
  5. 5. Which is generally a reason to prefer composition over inheritance?

    Small collaborating objects can be mixed freely and replaced, while inheritance fixes the relationship at compile time and exposes base-class internals.

Summary

  • S: give each class one reason to change; split calculation, presentation and storage.
  • O: add behaviour by adding code behind an abstraction instead of editing growing switch chains.
  • L: subtypes must honour the base contract; do not inherit when the promises differ.
  • I: prefer small role interfaces to fat ones nobody can fully implement.
  • D: depend on abstractions and inject them; this makes code testable.
  • Favour composition for "has-a" and immutability (records, init, readonly) as the default.
  • Use principles proportionately; the goal is code that is easy to change, not the most interfaces.

Next: Generics