Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

L — Liskov Substitution

Subtype must preserve base behavioral contract (no stronger preconditions, no weaker postconditions).

C#


class Rectangle
{
	public virtual int Width { get; set; }
	public virtual int Height { get; set; }
	public virtual int Area() => Width * Height;
}

class Square : Rectangle
{
	public override int Width
	{
		get => base.Width;
		set { base.Width = base.Height = value; }
	}
	public override int Height
	{
		get => base.Height;
		set { base.Width = base.Height = value; }
	}
}

interface IShape { int Area(); }

class ProperRectangle : IShape
{
	public int Width { get; set; }
	public int Height { get; set; }
	public int Area() => Width * Height;
}

class ProperSquare : IShape
{
	public int Side { get; set; }
	public int Area() => Side * Side;
}

// usage
IShape s1 = new ProperRectangle { Width = 3, Height = 4 };
IShape s2 = new ProperSquare { Side = 5 };
var total = s1.Area() + s2.Area();
next