Open/Closed Principle (OCP) in C# – SOLID Explained with Real Examples

The Open/Closed Principle (OCP) in C# is the second and one of the most practical principles of the SOLID design principles. It states that software entities should be open for extension but closed for modification. In real-world .NET applications, OCP helps developers add new features without breaking existing, stable code.

Understanding OCP is critical for writing scalable applications and is also a frequently asked interview topic for mid to senior-level .NET developers.

Open/Closed Principle (OCP) in C# with violation and solution example

What Is the Open/Closed Principle?

The Open/Closed Principle means that you should be able to extend the behavior of a class without modifying its source code. Instead of changing existing logic, new functionality should be added using abstraction, inheritance, or composition.

In short:

Add new code, don’t change working code.

This approach reduces the risk of introducing bugs into already-tested functionality.


Why OCP Is Important in C# Applications

In enterprise .NET projects, business requirements change frequently. If existing classes are modified repeatedly:

  • Bugs are introduced easily
  • Regression testing increases
  • Code becomes fragile and hard to maintain

By following OCP, developers protect stable code and make systems more flexible and future-ready.


OCP Violation Example in C#

Problematic Code (OCP Violation)

public class DiscountCalculator
{
    public double CalculateDiscount(string customerType, double amount)
    {
        if (customerType == "Regular")
            return amount * 0.1;
        else if (customerType == "Premium")
            return amount * 0.2;

        return 0;
    }
}

What’s wrong here?

  • Every new customer type requires modifying this class
  • Risk of breaking existing logic
  • Violates Open/Closed Principle

OCP-Compliant Solution in C#

Refactored Code (Following OCP)

public interface IDiscountStrategy
{
    double Calculate(double amount);
}

public class RegularCustomerDiscount : IDiscountStrategy
{
    public double Calculate(double amount) => amount * 0.1;
}

public class PremiumCustomerDiscount : IDiscountStrategy
{
    public double Calculate(double amount) => amount * 0.2;
}

public class DiscountCalculator
{
    private readonly IDiscountStrategy _discountStrategy;

    public DiscountCalculator(IDiscountStrategy discountStrategy)
    {
        _discountStrategy = discountStrategy;
    }

    public double CalculateDiscount(double amount)
    {
        return _discountStrategy.Calculate(amount);
    }
}

Why this follows OCP

  • New discount types can be added without modifying existing code
  • Code is easier to test
  • Logic is extensible and clean
  • Works well with Dependency Injection

Benefits of Using Open/Closed Principle

Applying OCP in C# provides several advantages:

  • Reduces regression bugs
  • Improves maintainability
  • Supports scalability
  • Encourages clean architecture
  • Enhances testability

As a result, applications become easier to evolve over time.


Real-World Use Cases of OCP

OCP is widely used in:

  • ASP.NET Core middleware and filters
  • Payment gateways and pricing rules
  • Notification systems (Email, SMS, Push)
  • Strategy-based business logic
  • Plugin-based architectures

Most extensible frameworks internally rely on OCP.


Common Interview Questions on OCP

Q: What is Open/Closed Principle?
A: Software entities should be open for extension but closed for modification.

Q: How do you achieve OCP in C#?
A: By using abstraction, interfaces, inheritance, and dependency injection.

Q: Is OCP always required?
A: No, but developers strongly recommend OCP in areas where requirements change frequently.


Conclusion

The Open/Closed Principle is essential for building scalable and robust C# applications. Although it may require additional abstraction initially, it saves significant effort in the long run. By following OCP, developers add new features safely without impacting existing functionality.

In the next post, we will cover the Liskov Substitution Principle (LSP) with practical C# examples.

You may also read Solid Principles to understand concept.


4 thoughts on “Open/Closed Principle (OCP) in C# – SOLID Explained with Real Examples”

  1. Pingback: Single Responsibility Principle (SRP) in C# – Clean Code

  2. Pingback: Liskov Substitution Principle in C# Explained with Examples

  3. Pingback: Interface Segregation Principle (ISP) in C# – SOLID Principles Explained - Mika Dev Hub

  4. Pingback: Design Patterns in .NET (C#) – Complete Guide & Best Practices

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top