Open/Closed Principle - SOLID Principles in c#

A class should be available for extension but closed for modification, according to the available/Closed Principle. This lets you add functionality without changing code.

A class should be open for extension but closed for modification,  when new requirements are generated under the Open/Closed Principle. In other words, we should be able to extend class behaviour without changing it. This is possible with inheritance and interfaces.

Les understand with an example
 

public interface IShape  {
   double Area();
}

public class Circle : IShape{
   public double Radius { get; set; }

   public double Area()   {
       return Math.PI * Radius * Radius;
   }
}

public class Rectangle : IShape{
   public double Width { get; set; }
   public double Height { get; set; }

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


Real Time Use: You download apps to expand your smartphone's capabilities, not open it.


This example uses an IShape interface with Circle and Rectangle classes. We can add a new shape class that implements the IShape interface without altering the existing ones.

Our code now adheres to both SRP and OCP. It is not necessary to modify the "AreaCalculator" if a new shape is introduced by deriving from the "Shape" abstract class.  

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