SOLID – Single Responsibility Principle in C#
Quick Answer: The Single Responsibility Principle says a class should have one responsibility and one reason to change. Keep unrelated work in separate classes. This makes your C# application easier to test, maintain and extend.
1. Why Do We Need the Single Responsibility Principle?
Imagine you manage fee payments for 1,000 students. Your application records payments, stores them, creates receipts and sends notifications.
Would you place every task inside one large class? Think about what happens when each task changes.
The Problem: One Class Handles Everything
Responsibility = work that a class owns.
Consider this school fee management example without SRP.
Example 1: One class handles multiple responsibilities
using System;
using System.Collections.Generic;
var manager = new SchoolFeeManager();
manager.ProcessPayment("STU-104", "Priya", 12500m);
class SchoolFeeManager
{
private readonly List<string> _payments = new();
public void ProcessPayment(
string studentId,
string studentName,
decimal amount)
{
// Validate the payment.
if (amount <= 0)
throw new ArgumentException("Invalid fee amount.");
// Store the payment.
_payments.Add(studentId + ":" + amount);
Console.WriteLine("Payment saved for " + studentName);
// Create the receipt.
string receipt = "RCP-" + studentId + "-" + amount;
Console.WriteLine("Receipt created: " + receipt);
// Send the notification.
Console.WriteLine("SMS sent to " + studentName);
}
}
Expected output
Payment saved for Priya Receipt created: RCP-STU-104-12500 SMS sent to Priya
This code works, but it gets hard to manage as requirements grow.
What Goes Wrong?
- Payment rules and receipt formatting share the same class.
- A receipt change can affect payment processing code.
- Testing one task may require testing the entire class.
- Notification changes can introduce risks to payment logic.
- Multiple developers may need to edit the same class.
Now think about 1,000 students and several changing requirements.
Visual 1: One Class With Multiple Responsibilities
The diagram shows four different tasks sharing one class and its change risks.
2. The Solution: Apply Single Responsibility Principle
We separate each task into a focused class. Each class owns one responsibility.
For this example, we will use four focused classes:
FeePaymentServicecoordinates the payment process.PaymentRepositorystores payment records.ReceiptGeneratorcreates payment receipts.SmsNotifierhandles SMS notifications.
Orchestration = coordinating the steps of one business task.
Visual 2: Separate Classes With Clear Responsibilities
The flow highlights the coordinator and each focused class in sequence.
Example 2: Separate the Responsibilities in C#
Purpose: process a fee payment using focused classes. This example uses .NET 8 or later and only built-in libraries.
Complete example: focused school fee classes
using System;
using System.Collections.Generic;
var payment = new FeePayment(
"STU-104", "Priya", 12500m);
var service = new FeePaymentService(
new PaymentRepository(),
new ReceiptGenerator(),
new SmsNotifier());
service.Process(payment);
public class FeePayment
{
public string StudentId { get; }
public string StudentName { get; }
public decimal Amount { get; }
public FeePayment(
string studentId,
string studentName,
decimal amount)
{
StudentId = studentId;
StudentName = studentName;
Amount = amount;
}
}
public class FeePaymentService
{
private readonly PaymentRepository _repository;
private readonly ReceiptGenerator _receiptGenerator;
private readonly SmsNotifier _notifier;
public FeePaymentService(
PaymentRepository repository,
ReceiptGenerator receiptGenerator,
SmsNotifier notifier)
{
_repository = repository;
_receiptGenerator = receiptGenerator;
_notifier = notifier;
}
public void Process(FeePayment payment)
{
if (payment.Amount <= 0)
throw new ArgumentException("Invalid fee amount.");
_repository.Save(payment);
string receipt = _receiptGenerator.Generate(payment);
_notifier.Send(payment.StudentName, receipt);
}
}
public class PaymentRepository
{
private readonly List<FeePayment> _payments = new();
public void Save(FeePayment payment)
{
_payments.Add(payment);
Console.WriteLine("Payment saved for " + payment.StudentName);
}
}
public class ReceiptGenerator
{
public string Generate(FeePayment payment)
{
string receipt = "RCP-" +
payment.StudentId + "-" + payment.Amount;
Console.WriteLine("Receipt created: " + receipt);
return receipt;
}
}
public class SmsNotifier
{
public void Send(string studentName, string receipt)
{
Console.WriteLine("SMS sent to " + studentName);
}
}
Expected output
Payment saved for Priya Receipt created: RCP-STU-104-12500 SMS sent to Priya
Important: The repository uses an in-memory list. It does not save data to a database. The SMS class prints a message instead of sending a real SMS.
3. Understand the Code
FeePaymentholds the payment details.FeePaymentServicecoordinates the payment workflow.PaymentRepositoryhandles payment storage.ReceiptGeneratorhandles receipt creation.SmsNotifierhandles notification delivery.
The coordinator still has a clear responsibility: complete the payment workflow. It delegates storage, receipt creation and notification work to other classes.
Without SRP vs With SRP
| Without SRP | With SRP |
|---|---|
| One class handles several tasks. | Each class owns focused work. |
| Changes can affect unrelated tasks. | Changes stay closer to their owner. |
| Testing can become difficult. | Classes can be tested separately. |
| Responsibilities are mixed. | Responsibilities are easier to understand. |
| One large class can grow over time. | New tasks can use focused classes. |
Terms to Remember
- SRP = one responsibility for each class.
- Responsibility = a reason that makes a class change.
- Separation of concerns = keeping different work in separate places.
- Orchestration = coordinating several steps in one workflow.
- Maintainability = how easily developers can understand and change code.
4. Common Mistakes and Best Practices
Mistake 1: Creating One Class for the Entire Feature
Do not place payment, receipt and notification logic together. Give each task a clear owner.
Mistake 2: Creating Too Many Tiny Classes
SRP does not mean one class for every method. Split classes when their responsibilities have different reasons to change.
Mistake 3: Treating Every Method as a Responsibility
A class can have several related methods. They should support one clear purpose.
Best Practices
- Ask why the class may need to change.
- Keep business rules close to their responsible class.
- Use constructor injection for required dependencies.
- Keep orchestration separate from detailed implementation work.
- Write focused unit tests for each responsibility.
5. How This Comes Up in Interviews
Question: What Is the Single Responsibility Principle?
What the interviewer expects: Explain one responsibility and one reason to change. Give a practical example.
Strong answer:
Single Responsibility Principle is the first SOLID principle. It says a class should have one responsibility and one reason to change. In a school fee application, payment storage, receipt creation and SMS notification should not share one large class. We separate these tasks into focused classes. This makes the code easier to test and maintain.
Follow-up Questions
- Does SRP mean one method per class? No. Related methods can belong together.
- Can a service coordinate other services? Yes. Its responsibility can be one clear workflow.
- How does SRP improve testing? Focused classes need fewer unrelated dependencies.
- Does SRP always mean more classes? Not always. Split only when responsibilities differ.
6. Hands-On Practice
Beginner
Find the different responsibilities inside a school fee manager. List each task separately.
Intermediate
Move receipt creation into a separate ReceiptGenerator class. Keep the output unchanged.
Advanced
Replace the in-memory repository with a database-backed implementation. Keep receipt and notification code independent from storage details.
7. Next Steps and Community
Previous article: SOLID Principles Introduction.
Next article: SOLID – Open/Closed Principle.
Try the exercises and share your implementation. Discuss other designs and help fellow developers learn.
Remember: Give every class one clear responsibility and one reason to change.
Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.
This is an excellent, beginner-friendly introduction to SRP! The restaurant analogy and the interview questions make it highly accessible for the Upgradix community.
To make the article even stronger and production-ready, consider addressing these few gaps:
Show the anti-pattern: Add a quick "bad code" example (a bloated class) before the refactored solution so readers see the problem first.
Warn against over-engineering: Remind beginners not to fragment their code too much—related operations should stay together.
Add real-world context: Briefly mention how SRP maps to modern .NET architecture (e.g., separating Controllers, Services, and Repositories).
Tease the next step: Add a closing sentence that transitions smoothly into the Open/Closed Principle (OCP) for the next article.
Great work making complex concepts simple!