0% found this document useful (0 votes)
4 views2 pages

Solid LSP Cs

The document demonstrates the Liskov Substitution Principle using a Rectangle and Square class in C#. It shows how the Square class overrides the Width and Height properties of the Rectangle class, leading to potential issues when substituting a Square for a Rectangle. The main method illustrates the calculation of area for both shapes, emphasizing the importance of adhering to the principle for proper object-oriented design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Solid LSP Cs

The document demonstrates the Liskov Substitution Principle using a Rectangle and Square class in C#. It shows how the Square class overrides the Width and Height properties of the Rectangle class, leading to potential issues when substituting a Square for a Rectangle. The main method illustrates the calculation of area for both shapes, emphasizing the importance of adhering to the principle for proper object-oriented design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

using static System.

Console;

namespace DotNetDesignPatternDemos.SOLID.LiskovSubstitutionPrinciple
{
// using a classic example
public class Rectangle
{
//public int Width { get; set; }
//public int Height { get; set; }

public virtual int Width { get; set; }


public virtual int Height { get; set; }

public Rectangle()
{

public Rectangle(int width, int height)


{
Width = width;
Height = height;
}

public override string ToString()


{
return $"{nameof(Width)}: {Width}, {nameof(Height)}: {Height}";
}
}

public class Square : Rectangle


{
//public new int Width
//{
// set { base.Width = base.Height = value; }
//}

//public new int Height


//{
// set { base.Width = base.Height = value; }
//}

public override int Width // nasty side effects


{
set { base.Width = base.Height = value; }
}

public override int Height


{
set { base.Width = base.Height = value; }
}
}

public class Demo


{
static public int Area(Rectangle r) => r.Width * r.Height;

static void Main(string[] args)


{
Rectangle rc = new Rectangle(2,3);
WriteLine($"{rc} has area {Area(rc)}");

// should be able to substitute a base type for a subtype


/*Square*/ Rectangle sq = new Square();
sq.Width = 4;
WriteLine($"{sq} has area {Area(sq)}");
}
}
}

You might also like