jj
SOLID Principles in C#
A beginner-friendly guide to writing clean and maintainable code using SOLID principles.
1. Single Responsibility Principle (SRP)
A class should have only one reason to change.
Example:
```
public class Invoice
{
public void Calculate() { }
}
public class InvoiceRepository
{
public void Save(Invoice invoice) { }
}
```
2. Open/Closed Principle (OCP)
Software should be open for extension but closed for modification.
Example:
```
public interface IDiscount
{
double GetDiscount();
}
public class StudentDiscount : IDiscount
{
public double GetDiscount() => 10;
}
```
3. Liskov Substitution Principle (LSP)
Derived classes should be replaceable with their base classes.
Example:
```
public interface IBird { }
public interface IFlyingBird
{
void Fly();
}
public class Sparrow : IFlyingBird
{
public void Fly() { }
}
```
4. Interface Segregation Principle (ISP)
Clients should not be forced to depend on methods they do not use.
Example:
```
public interface IWork
{
void Work();
}
public class Robot : IWork
{
public void Work() { }
}
```
5. Dependency Inversion Principle (DIP)
Depend on abstractions, not on concrete classes.
Example:
```
public interface IMessageService
{
void Send();
}
public class EmailService : IMessageService
{
public void Send() { }
}
public class Notification
{
private IMessageService _service;
```
public Notification(IMessageService service)
{
_service = service;
}
```
}
```
Conclusion
SOLID principles help developers write flexible, scalable, and maintainable code. They are widely used in real-world applications, especially in ASP.NET MVC projects.
```
Comments
Post a Comment