Master SOLID Principles in C#

Your comprehensive guide to writing clean, maintainable, and scalable C# code using SOLID principles

Practical Examples
Detailed Explanations
Best Practices
Start Learning

SOLID Principles

Single Responsibility Principle (SRP)

A class should have only one reason to change.

Key Points:

  • Each class should have a single, well-defined purpose
  • Reduces coupling between different parts of the system
  • Makes code more maintainable and testable

Common Violations:

  • Classes that handle both business logic and data access
  • Classes that perform multiple unrelated operations
  • Classes that mix UI and business logic

Open/Closed Principle (OCP)

Software entities should be open for extension but closed for modification.

Key Points:

  • Extend functionality without changing existing code
  • Use abstractions and inheritance
  • Implement new features through new classes

Implementation Strategies:

  • Use interfaces and abstract classes
  • Implement the Strategy pattern
  • Use composition over inheritance

Liskov Substitution Principle (LSP)

Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.

Key Points:

  • Subtypes must be substitutable for their base types
  • Maintain behavioral compatibility
  • Preserve contracts and invariants

Common Violations:

  • Throwing new exceptions in derived classes
  • Changing the behavior of inherited methods
  • Violating the contract of the base class

Interface Segregation Principle (ISP)

Clients should not be forced to depend on interfaces they do not use.

Key Points:

  • Keep interfaces small and focused
  • Split large interfaces into smaller ones
  • Clients should only know about methods they use

Benefits:

  • Reduced coupling between components
  • Better code organization
  • Easier maintenance and testing

Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Key Points:

  • Depend on abstractions, not concrete implementations
  • Use dependency injection
  • Invert the dependency direction

Implementation Methods:

  • Constructor injection
  • Property injection
  • Method injection

Practical Code Examples

Single Responsibility Principle Example

This example demonstrates a complete implementation of SRP in a user management system:


// Interfaces
public interface IUserRepository
{
    void Save(User user);
    User GetById(int id);
    void Update(User user);
    void Delete(int id);
}

public interface IEmailService
{
    void SendWelcomeEmail(string email);
    void SendPasswordResetEmail(string email);
}

public interface ILogger
{
    void LogInfo(string message);
    void LogError(string message);
}

// Concrete implementations
public class UserRepository : IUserRepository
{
    private readonly DbContext _context;

    public UserRepository(DbContext context)
    {
        _context = context;
    }

    public void Save(User user)
    {
        _context.Users.Add(user);
        _context.SaveChanges();
    }

    public User GetById(int id)
    {
        return _context.Users.Find(id);
    }

    public void Update(User user)
    {
        _context.Users.Update(user);
        _context.SaveChanges();
    }

    public void Delete(int id)
    {
        var user = _context.Users.Find(id);
        if (user != null)
        {
            _context.Users.Remove(user);
            _context.SaveChanges();
        }
    }
}

public class EmailService : IEmailService
{
    private readonly SmtpClient _smtpClient;
    private readonly string _fromEmail;

    public EmailService(SmtpClient smtpClient, string fromEmail)
    {
        _smtpClient = smtpClient;
        _fromEmail = fromEmail;
    }

    public void SendWelcomeEmail(string email)
    {
        var message = new MailMessage
        {
            From = new MailAddress(_fromEmail),
            Subject = "Welcome to Our Platform",
            Body = "Welcome! We're excited to have you on board.",
            IsBodyHtml = true
        };
        message.To.Add(email);
        _smtpClient.Send(message);
    }

    public void SendPasswordResetEmail(string email)
    {
        var message = new MailMessage
        {
            From = new MailAddress(_fromEmail),
            Subject = "Password Reset Request",
            Body = "Click here to reset your password.",
            IsBodyHtml = true
        };
        message.To.Add(email);
        _smtpClient.Send(message);
    }
}

public class FileLogger : ILogger
{
    private readonly string _logFilePath;

    public FileLogger(string logFilePath)
    {
        _logFilePath = logFilePath;
    }

    public void LogInfo(string message)
    {
        var logMessage = $"[INFO] {DateTime.Now}: {message}";
        File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
    }

    public void LogError(string message)
    {
        var logMessage = $"[ERROR] {DateTime.Now}: {message}";
        File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
    }
}

// Main service class
public class UserService
{
    private readonly IUserRepository _userRepository;
    private readonly IEmailService _emailService;
    private readonly ILogger _logger;

    public UserService(
        IUserRepository userRepository,
        IEmailService emailService,
        ILogger logger)
    {
        _userRepository = userRepository;
        _emailService = emailService;
        _logger = logger;
    }

    public void RegisterUser(User user)
    {
        try
        {
            _userRepository.Save(user);
            _emailService.SendWelcomeEmail(user.Email);
            _logger.LogInfo($"User {user.Name} registered successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Error registering user {user.Name}: {ex.Message}");
            throw;
        }
    }

    public void UpdateUser(User user)
    {
        try
        {
            _userRepository.Update(user);
            _logger.LogInfo($"User {user.Name} updated successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Error updating user {user.Name}: {ex.Message}");
            throw;
        }
    }

    public void DeleteUser(int userId)
    {
        try
        {
            _userRepository.Delete(userId);
            _logger.LogInfo($"User {userId} deleted successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Error deleting user {userId}: {ex.Message}");
            throw;
        }
    }
}
                    

Open/Closed Principle Example

This example shows a complete implementation of OCP using a payment processing system:


// Payment processing system
public interface IPaymentProcessor
{
    bool ProcessPayment(decimal amount);
    string GetPaymentMethod();
}

public abstract class PaymentProcessor : IPaymentProcessor
{
    protected readonly ILogger _logger;
    protected readonly string _currency;

    protected PaymentProcessor(ILogger logger, string currency = "USD")
    {
        _logger = logger;
        _currency = currency;
    }

    public abstract bool ProcessPayment(decimal amount);
    public abstract string GetPaymentMethod();

    protected void LogPayment(decimal amount, bool success)
    {
        var status = success ? "successful" : "failed";
        _logger.LogInfo($"Payment of {amount} {_currency} {status} using {GetPaymentMethod()}");
    }
}

public class CreditCardProcessor : PaymentProcessor
{
    private readonly string _cardNumber;
    private readonly string _cvv;
    private readonly string _expiryDate;

    public CreditCardProcessor(
        ILogger logger,
        string cardNumber,
        string cvv,
        string expiryDate,
        string currency = "USD") : base(logger, currency)
    {
        _cardNumber = cardNumber;
        _cvv = cvv;
        _expiryDate = expiryDate;
    }

    public override bool ProcessPayment(decimal amount)
    {
        try
        {
            // Simulate credit card processing
            var success = ValidateCard() && ProcessCardPayment(amount);
            LogPayment(amount, success);
            return success;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Credit card payment failed: {ex.Message}");
            return false;
        }
    }

    public override string GetPaymentMethod() => "Credit Card";

    private bool ValidateCard()
    {
        // Implement card validation logic
        return !string.IsNullOrEmpty(_cardNumber) && 
               !string.IsNullOrEmpty(_cvv) && 
               !string.IsNullOrEmpty(_expiryDate);
    }

    private bool ProcessCardPayment(decimal amount)
    {
        // Implement actual payment processing
        return true; // Simulated success
    }
}

public class PayPalProcessor : PaymentProcessor
{
    private readonly string _email;
    private readonly string _password;

    public PayPalProcessor(
        ILogger logger,
        string email,
        string password,
        string currency = "USD") : base(logger, currency)
    {
        _email = email;
        _password = password;
    }

    public override bool ProcessPayment(decimal amount)
    {
        try
        {
            // Simulate PayPal processing
            var success = ValidatePayPalAccount() && ProcessPayPalPayment(amount);
            LogPayment(amount, success);
            return success;
        }
        catch (Exception ex)
        {
            _logger.LogError($"PayPal payment failed: {ex.Message}");
            return false;
        }
    }

    public override string GetPaymentMethod() => "PayPal";

    private bool ValidatePayPalAccount()
    {
        // Implement PayPal account validation
        return !string.IsNullOrEmpty(_email) && !string.IsNullOrEmpty(_password);
    }

    private bool ProcessPayPalPayment(decimal amount)
    {
        // Implement actual PayPal payment processing
        return true; // Simulated success
    }
}

public class PaymentService
{
    private readonly IPaymentProcessor _paymentProcessor;
    private readonly ILogger _logger;

    public PaymentService(IPaymentProcessor paymentProcessor, ILogger logger)
    {
        _paymentProcessor = paymentProcessor;
        _logger = logger;
    }

    public bool ProcessPayment(decimal amount)
    {
        try
        {
            return _paymentProcessor.ProcessPayment(amount);
        }
        catch (Exception ex)
        {
            _logger.LogError($"Payment processing failed: {ex.Message}");
            return false;
        }
    }
}

// Usage example
public class Program
{
    public static void Main()
    {
        var logger = new FileLogger("payments.log");
        
        // Credit Card payment
        var creditCardProcessor = new CreditCardProcessor(
            logger,
            "4111111111111111",
            "123",
            "12/25"
        );
        var creditCardService = new PaymentService(creditCardProcessor, logger);
        creditCardService.ProcessPayment(100.00m);

        // PayPal payment
        var payPalProcessor = new PayPalProcessor(
            logger,
            "user@example.com",
            "password123"
        );
        var payPalService = new PaymentService(payPalProcessor, logger);
        payPalService.ProcessPayment(50.00m);
    }
}
                    

Liskov Substitution Principle Example

This example demonstrates a complete implementation of LSP in a shape hierarchy:


public abstract class Shape
{
    public abstract double CalculateArea();
    public abstract double CalculatePerimeter();
    public abstract bool IsValid();
}

public class Rectangle : Shape
{
    public double Width { get; private set; }
    public double Height { get; private set; }

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    public override double CalculateArea()
    {
        return Width * Height;
    }

    public override double CalculatePerimeter()
    {
        return 2 * (Width + Height);
    }

    public override bool IsValid()
    {
        return Width > 0 && Height > 0;
    }

    public void SetDimensions(double width, double height)
    {
        if (width <= 0 || height <= 0)
            throw new ArgumentException("Dimensions must be positive");
        
        Width = width;
        Height = height;
    }
}

public class Square : Shape
{
    public double Side { get; private set; }

    public Square(double side)
    {
        Side = side;
    }

    public override double CalculateArea()
    {
        return Side * Side;
    }

    public override double CalculatePerimeter()
    {
        return 4 * Side;
    }

    public override bool IsValid()
    {
        return Side > 0;
    }

    public void SetSide(double side)
    {
        if (side <= 0)
            throw new ArgumentException("Side length must be positive");
        
        Side = side;
    }
}

public class Circle : Shape
{
    public double Radius { get; private set; }
    private const double PI = Math.PI;

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double CalculateArea()
    {
        return PI * Radius * Radius;
    }

    public override double CalculatePerimeter()
    {
        return 2 * PI * Radius;
    }

    public override bool IsValid()
    {
        return Radius > 0;
    }

    public void SetRadius(double radius)
    {
        if (radius <= 0)
            throw new ArgumentException("Radius must be positive");
        
        Radius = radius;
    }
}

public class ShapeCalculator
{
    public static double CalculateTotalArea(IEnumerable shapes)
    {
        return shapes.Where(s => s.IsValid()).Sum(s => s.CalculateArea());
    }

    public static double CalculateTotalPerimeter(IEnumerable shapes)
    {
        return shapes.Where(s => s.IsValid()).Sum(s => s.CalculatePerimeter());
    }
}

// Usage example
public class Program
{
    public static void Main()
    {
        var shapes = new List
        {
            new Rectangle(5, 4),
            new Square(3),
            new Circle(2)
        };

        var totalArea = ShapeCalculator.CalculateTotalArea(shapes);
        var totalPerimeter = ShapeCalculator.CalculateTotalPerimeter(shapes);

        Console.WriteLine($"Total Area: {totalArea:F2}");
        Console.WriteLine($"Total Perimeter: {totalPerimeter:F2}");
    }
}
                    

Interface Segregation Principle Example

This example shows a complete implementation of ISP in a document processing system:


// Core interfaces
public interface IDocument
{
    string Title { get; set; }
    string Content { get; set; }
    DateTime CreatedDate { get; }
    DateTime ModifiedDate { get; }
}

public interface IPrintable
{
    void Print();
    void PrintToPdf();
}

public interface IScannable
{
    void Scan();
    void ScanToPdf();
}

public interface IFaxable
{
    void SendFax(string recipient);
    void ReceiveFax(string sender);
}

public interface IEmailable
{
    void SendEmail(string recipient);
    void ReceiveEmail(string sender);
}

// Document implementations
public class TextDocument : IDocument, IPrintable, IEmailable
{
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime CreatedDate { get; private set; }
    public DateTime ModifiedDate { get; private set; }

    public TextDocument(string title, string content)
    {
        Title = title;
        Content = content;
        CreatedDate = DateTime.Now;
        ModifiedDate = DateTime.Now;
    }

    public void Print()
    {
        Console.WriteLine($"Printing document: {Title}");
        // Implement actual printing logic
    }

    public void PrintToPdf()
    {
        Console.WriteLine($"Converting to PDF: {Title}");
        // Implement PDF conversion logic
    }

    public void SendEmail(string recipient)
    {
        Console.WriteLine($"Sending email to {recipient}: {Title}");
        // Implement email sending logic
    }

    public void ReceiveEmail(string sender)
    {
        Console.WriteLine($"Receiving email from {sender}: {Title}");
        // Implement email receiving logic
    }
}

public class ImageDocument : IDocument, IPrintable, IScannable
{
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime CreatedDate { get; private set; }
    public DateTime ModifiedDate { get; private set; }

    public ImageDocument(string title, string content)
    {
        Title = title;
        Content = content;
        CreatedDate = DateTime.Now;
        ModifiedDate = DateTime.Now;
    }

    public void Print()
    {
        Console.WriteLine($"Printing image: {Title}");
        // Implement actual printing logic
    }

    public void PrintToPdf()
    {
        Console.WriteLine($"Converting image to PDF: {Title}");
        // Implement PDF conversion logic
    }

    public void Scan()
    {
        Console.WriteLine($"Scanning image: {Title}");
        // Implement scanning logic
    }

    public void ScanToPdf()
    {
        Console.WriteLine($"Scanning image to PDF: {Title}");
        // Implement scan to PDF logic
    }
}

public class FaxDocument : IDocument, IFaxable
{
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime CreatedDate { get; private set; }
    public DateTime ModifiedDate { get; private set; }

    public FaxDocument(string title, string content)
    {
        Title = title;
        Content = content;
        CreatedDate = DateTime.Now;
        ModifiedDate = DateTime.Now;
    }

    public void SendFax(string recipient)
    {
        Console.WriteLine($"Sending fax to {recipient}: {Title}");
        // Implement fax sending logic
    }

    public void ReceiveFax(string sender)
    {
        Console.WriteLine($"Receiving fax from {sender}: {Title}");
        // Implement fax receiving logic
    }
}

// Document processor
public class DocumentProcessor
{
    public void ProcessDocument(IDocument document)
    {
        Console.WriteLine($"Processing document: {document.Title}");
        Console.WriteLine($"Created: {document.CreatedDate}");
        Console.WriteLine($"Modified: {document.ModifiedDate}");
        Console.WriteLine($"Content: {document.Content}");
    }

    public void PrintDocument(IPrintable document)
    {
        document.Print();
    }

    public void ScanDocument(IScannable document)
    {
        document.Scan();
    }

    public void SendFax(IFaxable document, string recipient)
    {
        document.SendFax(recipient);
    }

    public void SendEmail(IEmailable document, string recipient)
    {
        document.SendEmail(recipient);
    }
}

// Usage example
public class Program
{
    public static void Main()
    {
        var processor = new DocumentProcessor();

        // Text document
        var textDoc = new TextDocument("Report", "This is a text report");
        processor.ProcessDocument(textDoc);
        processor.PrintDocument(textDoc);
        processor.SendEmail(textDoc, "recipient@example.com");

        // Image document
        var imageDoc = new ImageDocument("Photo", "Image content");
        processor.ProcessDocument(imageDoc);
        processor.PrintDocument(imageDoc);
        processor.ScanDocument(imageDoc);

        // Fax document
        var faxDoc = new FaxDocument("Contract", "Contract content");
        processor.ProcessDocument(faxDoc);
        processor.SendFax(faxDoc, "123-456-7890");
    }
}
                    

Dependency Inversion Principle Example

This example demonstrates a complete implementation of DIP in a notification system:


// Core interfaces
public interface INotificationService
{
    void SendNotification(string recipient, string subject, string message);
}

public interface ILogger
{
    void LogInfo(string message);
    void LogError(string message);
}

public interface IConfigurationService
{
    string GetSetting(string key);
    void SaveSetting(string key, string value);
}

// Concrete implementations
public class EmailNotificationService : INotificationService
{
    private readonly ILogger _logger;
    private readonly IConfigurationService _config;
    private readonly SmtpClient _smtpClient;

    public EmailNotificationService(
        ILogger logger,
        IConfigurationService config,
        SmtpClient smtpClient)
    {
        _logger = logger;
        _config = config;
        _smtpClient = smtpClient;
    }

    public void SendNotification(string recipient, string subject, string message)
    {
        try
        {
            var mailMessage = new MailMessage
            {
                From = new MailAddress(_config.GetSetting("FromEmail")),
                Subject = subject,
                Body = message,
                IsBodyHtml = true
            };
            mailMessage.To.Add(recipient);

            _smtpClient.Send(mailMessage);
            _logger.LogInfo($"Email sent to {recipient}");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to send email to {recipient}: {ex.Message}");
            throw;
        }
    }
}

public class SmsNotificationService : INotificationService
{
    private readonly ILogger _logger;
    private readonly IConfigurationService _config;

    public SmsNotificationService(
        ILogger logger,
        IConfigurationService config)
    {
        _logger = logger;
        _config = config;
    }

    public void SendNotification(string recipient, string subject, string message)
    {
        try
        {
            // Implement SMS sending logic
            _logger.LogInfo($"SMS sent to {recipient}");
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to send SMS to {recipient}: {ex.Message}");
            throw;
        }
    }
}

public class FileLogger : ILogger
{
    private readonly string _logFilePath;

    public FileLogger(string logFilePath)
    {
        _logFilePath = logFilePath;
    }

    public void LogInfo(string message)
    {
        var logMessage = $"[INFO] {DateTime.Now}: {message}";
        File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
    }

    public void LogError(string message)
    {
        var logMessage = $"[ERROR] {DateTime.Now}: {message}";
        File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
    }
}

public class AppSettingsConfiguration : IConfigurationService
{
    private readonly Dictionary _settings;

    public AppSettingsConfiguration()
    {
        _settings = new Dictionary();
    }

    public string GetSetting(string key)
    {
        return _settings.TryGetValue(key, out var value) ? value : null;
    }

    public void SaveSetting(string key, string value)
    {
        _settings[key] = value;
    }
}

// Main service
public class NotificationManager
{
    private readonly INotificationService _notificationService;
    private readonly ILogger _logger;

    public NotificationManager(
        INotificationService notificationService,
        ILogger logger)
    {
        _notificationService = notificationService;
        _logger = logger;
    }

    public void SendWelcomeNotification(string recipient)
    {
        try
        {
            _notificationService.SendNotification(
                recipient,
                "Welcome to Our Service",
                "Thank you for joining our service!"
            );
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to send welcome notification: {ex.Message}");
            throw;
        }
    }

    public void SendPasswordResetNotification(string recipient)
    {
        try
        {
            _notificationService.SendNotification(
                recipient,
                "Password Reset Request",
                "Click here to reset your password."
            );
        }
        catch (Exception ex)
        {
            _logger.LogError($"Failed to send password reset notification: {ex.Message}");
            throw;
        }
    }
}

// Usage example
public class Program
{
    public static void Main()
    {
        // Setup dependencies
        var logger = new FileLogger("notifications.log");
        var config = new AppSettingsConfiguration();
        config.SaveSetting("FromEmail", "noreply@example.com");

        // Create notification service
        var smtpClient = new SmtpClient();
        var emailService = new EmailNotificationService(logger, config, smtpClient);
        
        // Create notification manager
        var notificationManager = new NotificationManager(emailService, logger);

        // Send notifications
        notificationManager.SendWelcomeNotification("user@example.com");
        notificationManager.SendPasswordResetNotification("user@example.com");
    }
}
                    

Best Practices & Implementation Guidelines

Design Patterns

  • Use Repository Pattern for data access
  • Implement Unit of Work for transaction management
  • Apply Factory Pattern for object creation
  • Use Strategy Pattern for interchangeable algorithms

Testing Strategies

  • Write unit tests for each class
  • Use mocking frameworks for dependencies
  • Implement integration tests for components
  • Follow AAA pattern (Arrange, Act, Assert)

Code Organization

  • Follow Clean Architecture principles
  • Use proper folder structure
  • Implement proper namespacing
  • Keep related code together

Learning Resources

Books

Video Courses

Online Resources