Open/Closed Principle - SOLID Principles in c#
- Posted on
- Asp .Net
- By Deepak Talwar
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.