Share via


Liskov Substitution Principle

If you are following the Software Design Principles while developing an application, the first thing that comes to your mind is the Liskov Substitution Principle. In this principle it is stated that the base class objects can always be substituted with the derived class objects. 

"Derived classes must be able to substitute for their base classes"

Let us take an example  :

public class  Rectangle
{
 
    public int  Width {get;set;}
    public int  Height {get; set;}
}

Now let us consider a Square. We can easily do that like this : 

public class  Square : Rectangle
{
 
}

But do they actually work?  

If we specify 
Rectangle r = new Square();

there will be two properties Width and Height and for which you can define different values. So, to substitute the Rectangle with Square completely, we need to override the Width and Height to return the same values.

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

Now this will do the trick, as the Rectangle now completely replace the Square object. The Width and Height will always return the same value.

See Also