![]() Here, first, we need a generic base class such as Fruit which is going to be the base class for both Apple and Orange. Let’s modify the previous example to follow the Liskov Substitution Principle. ![]() Example Using the Liskov Substitution Principle in C# Let us see how to overcome the design issue and makes the application follow Liskov Substitution Principle. That means there is some issue with our software design. So, in this case, if we are getting the color of Apple instead of Orange, then it follows the Liskov Substitution Principle. The Liskov Substitution Principle in C# states that even the child object is replaced with the parent, the behavior should not be changed. Apple storing the Orange object, the behavior is also changed. That means once the child object is replaced i.e. apple.GetColor(), then we are getting the color of the Orange not the color of Apple. Apple apple = new Orange() and when we call the GetColor i.e. So, we can store the child class object in the Parent Reference variable i.e. namespace SOLID_PRINCIPLES.LSPĪs you can see in the above example, Apple is the base class and Orange is the child class i.e. ![]() The point is that an Orange cannot be replaced by an Apple, which results in printing the color of the apple as Orange as shown in the below example. Then we create the Orange class which inherits the Apple class as well as overrides the GetColor method of the Apple class. In the following example, first, we create the Apple class with the method GetColor. Let us first understand one example without using the Liskov Substitution Principle in C#. Example: Without using the Liskov Substitution Principle in C#: So here, in this case, the son can’t simply replace his father even though both belong to the same family. ![]() If you are not getting this point properly, don’t worry, we will see some real-time examples to understand this concept.įor example, a father is a teacher whereas his son is a doctor. inheritance relationships, then, if we can successfully replace the object/instance of a parent class with an object/instance of the child class, without affecting the behavior of the base class instance, then it is said to be in Liskov Substitution Principle. In simple words we can say that, when we have a base class and child class relationships i.e. This principle states that, if S is a subtype of T, then objects of type T should be replaced with the objects of type S. The Liskov Substitution Principle is a Substitutability principle in object-oriented programming Language. What is the Liskov Substitution Principle in C#? Data Structures and Algorithms Tutorials. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |