wasAsked.

SOLID Principles, especially Liskov Substitution Principle with examples

EPAM · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

The Liskov Substitution Principle says code using a base abstraction should continue to behave correctly when given any valid subtype. A subtype must honor the base contract: it should not demand stronger preconditions, promise weaker results, or introduce surprising failures. A classic violation is a writable rectangle abstraction with a square subtype, because independently setting width and height conflicts with a square's invariant. Model capabilities honestly instead: ```csharp public interface IShape { decimal Area { get; } } public sealed record Rectangle(decimal Width, decimal Height) : IShape { public decimal Area => Width * Height; } public sealed record Square(decimal Side) : IShape { public decimal Area => Side * Side; } static decimal TotalArea(IEnumerable<IShape> shapes) => shapes.Sum(shape => shape.Area); ``` Both implementations satisfy the read-only shape contract without pretending they support incompatible mutation. LSP is not “use inheritance”; it is a test of behavioral substitutability. Contract tests applied to every implementation are a practical way to detect violations.

Pooja Parmar · · 0 likes

Sign in to add your answer

Related interview topics