Junior SOLID

What is an example of violating LSP in .NET code?

Example (Violation of LSP):

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 = 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.

More from Design Patterns in C#

All questions for this course