Introduction
C# is an object-oriented programming language. These days whenever you talk about object-oriented programming you hear the acronym, SOLID. These are five design principles introduced by Michael Feathers to make our object-oriented applications easy to understand, maintain, and expand as future requirements change. Today, we will look at the third principle with an example. I covered the first two principles in my previous articles.
The SOLID principles
There are five principles to follow to ensure our application meets the SOLID requirements. These are as below.
- Single Responsibility Principle (SRP)
- Open Closed Principle (OCP)
- Liskov Substitution Principle (LSP)
- Interface Segregation Principle (ISP)
- Dependency Inversion Principle (DIP)
The Liskov Substitution Principle (LSP)
The Liskov Substitution Principle (LSP) states that an instance of a child class must replace an instance of the parent class without affecting the results that we would get from an instance of the base class itself. This will ensure the class and ultimately the whole application is very robust and easy to maintain and expand, if required. Let us look at this with an example.
Let us create a new .NET Core 3.1 console application in Visual Studio 2019 Community Edition as below.


Inside this project, I have created a new class file “LiskovSubstitutionPrinciple”. In this file, I create the following base and child classes.
// Not following the Liskov Substitution Principle
public class AccessDataFile
{
public string FilePath { get; set; }
public virtual void ReadFile()
{
// Read File logic
Console.WriteLine($"Base File {FilePath} has been read");
}
public virtual void WriteFile()
{
//Write File Logic
Console.WriteLine($"Base File {FilePath} has been written");
}
}
public class AdminDataFileUser : AccessDataFile
{
public override void ReadFile()
{
// Read File logic
Console.WriteLine($"File {FilePath} has been read");
}
public override void WriteFile()
{
//Write File Logic
Console.WriteLine($"File {FilePath} has been written");
}
}
public class RegularDataFileUser : AccessDataFile
{
public override void ReadFile()
{
// Read File logic
Console.WriteLine($"File {FilePath} has been read");
}
public override void WriteFile()
{
//Write File Logic
throw new NotImplementedException();
}
} 
Join the conversation! Your thoughts help the community grow.