Applying SOLID Principles in C#: Examples and Best Practices

Single Responsibility Principle (SRP)

This principle states that each class should have a single responsibility. It emphasizes that a class should perform one specific function and not have too many reasons to change.

Example: Managing user information and sending email notifications.

class UserManager {
  public void CreateUser(UserData userData) {
    // Logic to create a user
  }
}

class EmailService {
  public void SendEmail(EmailData emailData) {
    // Logic to send an email
  }
}

Open/Closed Principle (OCP)

This principle encourages extending functionality by adding new code rather than modifying existing code.

Example: Handling different payment methods in an e-commerce application.

abstract class PaymentProcessor {
  public abstract void ProcessPayment();
}

class CreditCardPaymentProcessor : PaymentProcessor {
  public override void ProcessPayment() {
    // Logic to process credit card payment
  }
}

class PayPalPaymentProcessor : PaymentProcessor {
  public override void ProcessPayment() {
    // Logic to process PayPal payment
  }
}

Liskov Substitution Principle (LSP)

This principle asserts that objects of a derived class should be substitutable for objects of the base class without affecting the correctness of the program.

Example: Managing geometric shapes.

abstract class Shape {
  public abstract double CalculateArea();
}

class Rectangle : Shape {
  public override double CalculateArea() {
    // Logic to calculate area of rectangle
  }
}

class Square : Shape {
  public override double CalculateArea() {
    // Logic to calculate area of square
  }
}

Interface Segregation Principle (ISP)

This principle advises breaking interfaces into smaller ones to avoid forcing classes to implement methods they don't need.

Example: Interfaces for updating and displaying data.

interface IUpdateableFeature {
  void UpdateFeature();
}

interface IDisplayableFeature {
  void DisplayFeature();
}

Dependency Inversion Principle (DIP)

This principle suggests using dependency injection to manage dependencies.

Example: Using dependency injection to manage dependencies.

class OrderProcessor {
  private readonly DBConnection _dbConnection;
  private readonly EmailService _emailService;

  public OrderProcessor(DBConnection dbConnection, EmailService emailService) {
    _dbConnection = dbConnection;
    _emailService = emailService;
  }
}

Remember that applying SOLID principles in C# should be done flexibly based on the specific purpose of your project and your understanding of SOLID and C#.