Liskov Substitution Principle -SOLID Principles in c#

This principle is an extension of the Open Closed Principle, so newly derived classes must extend base classes without changing behaviour.

Liskov Substitution Principle staes that superclass objects can be replaced by subclass objects without compromising program correctness. A subclass should be able to replace its superclass without any difficulties. 

public class Rectangle{
   public virtual double Width { get; set; }
   public virtual double Height { get; set; }

   public double Area()
   {
       return Width * Height;
   }
}

 

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

   

 public override double Height   {
       get => base.Height;
       set
       {
           base.Width = value;
           base.Height = value;
       }
   }
}


You shouldn't have to modify any derived class to act like a parent class.


We have a Rectangle class and a Square class that inherits from it. The Square class overrides Width and Height to maintain equality. We can utilise Square objects when Rectangle objects are anticipated.

Here, GetTextFromFiles() only returns IReadOnlySqlFile objects.
Now we can declare our design follows LSP. We solved the problem utilising interface segregation principle (ISP), abstraction, and responsibility separation.

Author
Full Stack Developer

Deepak Talwar

Technical Architect & Full Stack Developer with 18+ years of Professional Experience in Microsoft Technologies & PHP Platform. Hands on experience with C#, VB, ASP.NET, ASP.NET MVC, ASP.NET Core, ASP.NET Web API, Linq, ADO.NET, Entity Framework, Entity Framework Core, Sql Server, MYSQL, NoSql, Javascript, Angular, jQuery, AWS, Azure, React, Angular, Laravel, Codeingiter, Serenity, VBA, Cloud Computing, Microservices, Design Patterns, Software Architecture, Web Design and Development.

Related Post