LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

SOLID - Open/Closed Principle

Open/Closed Principle, the second principle in SOLID. It says that software entities should be open for extension but closed for modification. This means we should be able to add new features without repeatedly changing existing, tested code. It is useful in payment systems, notification services and other applications that support different implementations.

SOLID Open/Closed Principle in C# – Extend Code Without Changing Existing Logic

Quick Answer: The Open/Closed Principle says software should be open for extension but closed for modification. You should add new behaviour without repeatedly changing tested business logic. In C#, interfaces, abstractions and polymorphism help us achieve this.

1. Why Do We Need the Open/Closed Principle?

Imagine you manage billing for 1,000 hospital services. How will you add new billing rules without changing existing code every time?

Think about consultation fees, laboratory tests and pharmacy bills. Later, the hospital may introduce radiology services. Should we keep changing the same billing method?

The problem: Billing without the Open/Closed Principle

We can start with a simple method and check each service type.

Example 1: Hospital billing without an abstraction

Purpose: Calculate charges using a service type.

Prerequisite: .NET 8 SDK or later.

using System;

decimal CalculateBill(string serviceType, decimal amount)
{
    if (serviceType == "Consultation")
        return amount + 100;

    if (serviceType == "Laboratory")
        return amount + 50;

    if (serviceType == "Pharmacy")
        return amount + 20;

    throw new ArgumentException("Unknown service");
}

Console.WriteLine(CalculateBill("Consultation", 500));
Console.WriteLine(CalculateBill("Laboratory", 300));
Console.WriteLine(CalculateBill("Pharmacy", 200));

Expected output

600
350
220

This works, but it gets harder to manage as services grow.

What goes wrong?

  1. Every new service needs another condition.
  2. Existing billing logic changes again and again.
  3. One change can affect services that already work.
  4. Testing becomes harder as conditions increase.

Now think about 1,000 hospital services. The same method can become difficult to maintain.

2. The Solution: Apply the Open/Closed Principle

We can define one common contract for hospital charges.

Each service then provides its own billing calculation. The invoice does not need to know each service type.

Interface = a contract that defines what a class must provide.

Polymorphism = using different implementations through one common type.

Example 2: Define a common hospital charge contract

Purpose: Give every billing service the same calculation method.

public interface IHospitalCharge
{
    string ServiceName { get; }

    decimal CalculateAmount();
}

Example 3: Add separate service implementations

public class ConsultationCharge : IHospitalCharge
{
    public string ServiceName => "Consultation";

    public decimal CalculateAmount() => 600;
}

public class LaboratoryCharge : IHospitalCharge
{
    public string ServiceName => "Laboratory";

    public decimal CalculateAmount() => 350;
}

public class PharmacyCharge : IHospitalCharge
{
    public string ServiceName => "Pharmacy";

    public decimal CalculateAmount() => 220;
}

Example 4: Create an invoice that accepts the contract

using System;
using System.Collections.Generic;

public class HospitalInvoice
{
    public void Print(IEnumerable<IHospitalCharge> charges)
    {
        decimal total = 0;

        foreach (IHospitalCharge charge in charges)
        {
            decimal amount = charge.CalculateAmount();
            Console.WriteLine(
                $"{charge.ServiceName}: {amount}");

            total += amount;
        }

        Console.WriteLine($"Total: {total}");
    }
}

Example 5: Run the complete billing example

using System;
using System.Collections.Generic;

var charges = new List<IHospitalCharge>
{
    new ConsultationCharge(),
    new LaboratoryCharge(),
    new PharmacyCharge()
};

var invoice = new HospitalInvoice();
invoice.Print(charges);

Expected output

Consultation: 600
Laboratory: 350
Pharmacy: 220
Total: 1170

Important: These examples form one application. Put the interface, service classes and invoice class in the same project. Keep the final runner in the application's entry point.

Now add a new service

The hospital now offers radiology services. We can add one new class.

Example 6: Extend billing with radiology

public class RadiologyCharge : IHospitalCharge
{
    public string ServiceName => "Radiology";

    public decimal CalculateAmount() => 900;
}

Add the new implementation to the collection:

charges.Add(new RadiologyCharge());

invoice.Print(charges);

Expected output after adding radiology

Consultation: 600
Laboratory: 350
Pharmacy: 220
Radiology: 900
Total: 2070

Notice what did not change. The invoice calculation still uses the same code.

3. How the Open/Closed Principle Works

The following connected diagrams show two different designs. The first uses repeated conditions. The second uses an extension contract.

Design A: Conditions grow inside one billing method

Hospital billing method One method handles every service Service type conditions if / else checks Add another condition Change existing billing code Retest existing billing paths

The existing billing method changes whenever another service type is introduced.

Design B: New services extend a shared contract

HospitalInvoice Uses the shared contract IHospitalCharge Shared interface Consultation Charge Laboratory Charge Pharmacy Charge RadiologyCharge New implementation Add new service

The invoice uses one contract. New billing classes implement it without changing the invoice logic.

Invoice logic Abstraction Existing services New extension

4. Without OCP vs With OCP

How the two billing designs handle new services
Without Open/Closed With Open/Closed
Add another condition. Add another implementation.
Change the existing billing method. Keep the invoice logic unchanged.
Existing code needs repeated testing. Test the new implementation and integration.
Conditions grow with service types. New types follow the same contract.

The idea to remember

  • Open for extension = add new behaviour.
  • Closed for modification = avoid changing stable existing code.
  • Interface = a contract shared by different services.
  • Implementation = a class that provides the actual behaviour.
  • Polymorphism = use different classes through one common type.

5. Step-by-Step Code Breakdown

  1. IHospitalCharge: Defines the common billing contract.
  2. Service classes: Each class calculates its own charge.
  3. HospitalInvoice: Works with the interface, not concrete classes.
  4. RadiologyCharge: Adds new behaviour through another implementation.
  5. Collection: Holds different service objects through one interface type.

The invoice does not need to know every service class. It only needs the shared contract.

6. Common Mistakes and Best Practices

Mistake 1: Keeping a large switch statement

Wrong: Add another switch case for every new service.

Why it fails: The same method keeps changing.

Better: Move each service calculation into its own implementation.

Mistake 2: Creating an interface for every class

Wrong: Add abstractions without a clear reason.

Why it fails: Extra types can make simple code harder to follow.

Better: Introduce an interface when different implementations are expected.

Mistake 3: Changing the contract for every new service

Wrong: Keep adding service-specific methods to the interface.

Why it fails: Existing implementations may need changes.

Better: Keep the contract small and stable.

Mistake 4: Treating OCP as a rule against all changes

Wrong: Never change existing code.

Why it fails: Requirements and defects can still need changes.

Better: Protect stable behaviour while allowing planned extension.

Architect tip: Do not add abstractions just to follow a principle. Use them where change is likely and where the abstraction makes that change safer.

7. Open/Closed Principle in Real Projects

This principle is useful when one application supports several behaviours.

  • Payment systems: Add UPI, card or wallet payment handlers.
  • Notification systems: Add email, SMS or push notification handlers.
  • File exports: Add PDF, CSV or Excel export implementations.
  • Discount rules: Add new discount policies without changing checkout logic.
  • Cloud storage: Add storage providers behind a shared contract.

Does OCP mean existing code never changes?

No. It means we design important extension points carefully. A new requirement may still expose a poor abstraction. In that case, refactoring can be the right choice.

What about dependency injection?

Dependency injection can supply implementations to a class. It helps keep the high-level code independent of specific service classes. For example, an ASP.NET Core application can register several implementations and select them through a suitable design.

8. Interview Questions and Answers

Q1. What is the Open/Closed Principle?

Strong answer: The Open/Closed Principle says a software unit should be open for extension but closed for modification. We should add new behaviour without repeatedly changing stable business logic. In the hospital billing example, we add a new charge class instead of changing the invoice calculation.

Q2. How do you implement OCP in C#?

We can use interfaces, abstract classes and polymorphism. The main class depends on an abstraction. New implementations provide new behaviour through that abstraction.

Q3. Is an interface mandatory for OCP?

No. Interfaces are one common approach. Abstract classes, delegates and composition can also help. Choose the design that fits the expected changes.

Q4. What is the difference between OCP and dependency inversion?

OCP focuses on extending behaviour without changing stable code. Dependency inversion focuses on depending on abstractions rather than concrete details. They often support each other.

Q5. Can OCP make a design too complex?

Yes. Too many abstractions can make code harder to understand. Introduce extension points where change is likely. Keep simple, stable code simple.

9. Hands-On Practice

Beginner: Add an emergency service

Add an EmergencyCharge class that implements IHospitalCharge. Return a sample charge of 1,500. Add it to the invoice collection.

Intermediate: Add a new billing rule

Create a new hospital service with its own calculation. Keep HospitalInvoice unchanged. Confirm that the total includes the new charge.

Advanced: Use dependency injection

Move service selection into an ASP.NET Core application. Register the implementations with dependency injection. Decide how the correct service should be selected for each request.

10. Next Steps

Previous article: SOLID - Single Responsibility Principle.

Next article: SOLID - Liskov Substitution Principle.

Try the exercises and share your implementation with the Upgradix community. Explain where you used an abstraction and why it helped.

Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.