Liskov C#

Hello, how are you programmer friends? Today I bring this blog to talk about the Liskov’s substitution principle and with an example since it is an important topic for object-oriented programming, so let’s start:
First let’s talk about Liskov’s principle, this is about how when having a superclass and making a subclass it must replace the superclass without breaking the application or its functionality, so the important thing in sublcases is to make them inherit elements in the class for reuse.
taking into account what the Liskov’s principle is, we will now see an example:
or
here we have a Rectangle class and a Cube sublcase, what we would normally do is inherit the Rectanlge class but in this case we are going to see the error case:
using System;
class Program
{
static void Main(string[] args)
{
Square aSquare = new Square();
try
{
aSquare.Width = 12;
aSquare.Height = 8;
Console.WriteLine("aSquare width: {0}", aSquare.Width);
Console.WriteLine("aSquare height: {0}", aSquare.Height);
Console.WriteLine("aSquare size: {0}", aSquare.Size);
Console.WriteLine("aSquare area: {0}", aSquare.Area());
Console.WriteLine(aSquare.ToString());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
As we can see in the example, what we are doing here is calling the Square class directly instead of inheriting it from Rectanlge and therefore we cannot use Rectanlge objects.
the correct way to do this is to call Rectangle to inherit it when creating the subclass.
class Square : Rectangle
With all this we can conclude that it is important to correctly inherit the elements of a class if we want to use them since this could cause errors in our program and it is good to understand how to handle classes correctly.
well that’s all for the moment we don’t see in the next one.