👉 Full lesson with practice questions on DevLadder (free, lesson 3 of 8 in the SOLID Principles with Examples course)
If S is a subtype of T, objects of type T may be replaced by objects of type S without breaking the program. Subclasses must honour the base class's contract: no stronger preconditions, no weaker postconditions, no surprise exceptions.
// ❌ Classic violation: Square changes Rectangle's behaviour public class Rectangle { public virtual int Width { get; set; } public virtual int Height { get; set; } public int Area => Width * Height; } public class Square : Rectangle { public override int Width { set { base.Width = value; base.Height = value; } } public override int Height { set { base.Width = value; base.Height = value; } } } void Resize(Rectangle r) { r.Width = 5; r.Height = 4; Debug.Assert(r.Area == 20); } // fails for Square (16) // ✅ Model what they share, not a false "is-a" public interface IShape { int Area { get; } } public record Rect(int Width, int Height) : IShape { public int Area => Width * Height; } public record Sq(int Side) : IShape { public int Area => Side * Side; } LSP smells: throw new NotSupportedException() in an override, if (x is SpecialSubclass) checks in callers, overrides that do nothing.
Interview questions on SOLID Principles with Examples
What are the SOLID principles? Explain each briefly.
- Single Responsibility: one reason to change per class.
- Open/Closed: extend behaviour by adding code, not modifying existing code.
- Liskov Substitution: subclasses must work anywhere the base class works.
- Interface Segregation: small client-specific interfaces instead of a fat one.
- Dependency Inversion: high- and low-level modules depend on abstractions; inject dependencies.
Follow with one concrete example from your own project, e.g. "payment providers behind IPaymentGateway, registered in DI: that's OCP and DIP."
Give a real example of the Single Responsibility Principle.
An InvoiceService that calculates totals, writes to SQL and sends email has three reasons to change. Split it into InvoiceCalculator, IInvoiceRepository and IInvoiceSender, with a small workflow class orchestrating them. Now an SMTP-to-SendGrid change touches only the sender, and each part has focused unit tests.
How do you implement the Open/Closed Principle in C#?
Through abstractions and polymorphism: define an interface (IDiscountRule, IExportFormatter), implement each variant as its own class, and let the consumer receive IEnumerable<IDiscountRule> from DI. Adding a variant means a new class and registration; no existing, tested code changes. Other OCP tools: Strategy, Decorator, middleware, filters, events.
Read the full lesson with progress tracking and the rest of the course on DevLadder: free step-by-step tutorials and interview questions for developers.
Next in the course: I: Interface Segregation Principle →