Junior
From PDF
SOLID
Design Patterns & SOLID
What is an example of violating LSP in .NET code?
Short answer: Example (Violation of LSP): public class Rectangle
Example code
{
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 = base.Height = value; }
}
public override int Height
{
set { base.Width = base.Height = value; }
}
} Now if you substitute Rectangle with Square: Rectangle rect = new Square();
rect.Width = 5;
rect.Height = 10; Console.WriteLine(rect.Area()); // Outputs 100, but logically expected 50 ❌ The behavior is incorrect — this is a violation of LSP.
Real-world example (ShopNest)
Open/Closed in ShopNest: add a new payment method by adding a class, not by editing a giant switch in CheckoutService.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png