Roadmap › SOLID Principles with Examples › Module: L, I and D
Lessons in this course (8)
3. L — Liskov Substitution Principle
Intermediate★ Must knowLesson 3 of 8
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.
csharp
// ❌ 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.