Tuesday, May 2, 2023

SOLID - Liskov Substitution Principle explanation with sample C# code

The Liskov Substitution Principle (LSP) is a principle in object-oriented programming that states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In other words, a subclass should be able to be used wherever its parent class can be used.

Here is an example of how to implement the LSP in C#:
public class Rectangle
{
    public virtual int Width { get; set; }
    public virtual int Height { get; set; }

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

public 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.Height = base.Width = value;
    }
}
In this example, we have a base class called 'Rectangle' with two properties, 'Width' and 'Height', and a method called 'Area' that calculates the area of the rectangle.

We then have a derived class called 'Square' that inherits from 'Rectangle'. The 'Square' class overrides the 'Width' and 'Height' properties to always have the same value, which makes a square.

By implementing the 'Square' class in this way, we are adhering to the LSP. We can use a 'Square' object wherever a 'Rectangle' object is expected, and the program will continue to work correctly.

Overall, adhering to the LSP helps us create code that is more flexible and easier to maintain over time. We can use polymorphism to create more abstract and generic code, and we can substitute objects of one class with objects of another class without affecting the correctness of our program.

No comments:

Post a Comment