SOLID: Single Responsibility Principle in C#

The Single Responsibility Principle (SRP) is a fundamental concept in object-oriented programming that states that a class or module should have only one responsibility, i.e., it should have only one reason to change. This principle helps to improve the modularity, maintainability, and extensibility of the code.

In C#, SRP can be achieved by breaking down a class or module into smaller, more focused units of functionality, each with a single responsibility. This can be accomplished through various design patterns such as the Strategy pattern, the Command pattern, or the Adapter pattern.

Let's take a look at an example to see how SRP can be applied in C#.

using System;

namespace SRPExample
{
    public interface IShape
    {
        double GetArea();
    }

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

        public double GetArea()
        {
            return Width * Height;
        }
    }

    public class Circle : IShape
    {
        public double Radius { get; set; }

        public double GetArea()
        {
            return Math.PI * Radius * Radius;
        }
    }

    public class AreaCalculator
    {
        public double Calculate(IShape shape)
        {
            return shape.GetArea();
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var rectangle = new Rectangle { Width = 10, Height = 5 };
            var circle = new Circle { Radius = 7 };

            var calculator = new AreaCalculator();

            Console.WriteLine($"Rectangle area: {calculator.Calculate(rectangle)}");
            Console.WriteLine($"Circle area: {calculator.Calculate(circle)}");

            Console.ReadLine();
        }
    }
}

In this example, we have an interface IShape that defines a single method GetArea(). We have two classes, Rectangle and Circle, that implements this interface and provides their own implementations of the GetArea() method. We also have a class AreaCalculator that takes an IShape object and calculates its area using the GetArea() method.

By separating the responsibility of calculating the area of a shape into a separate class, we have made the code more modular and extensible. We can easily add new shapes by implementing the IShape interface and provide a GetArea() method.

In summary, the Single Responsibility Principle (SRP) is a fundamental concept in object-oriented programming that states that a class or module should have only one responsibility. In C#, SRP can be achieved by breaking down a class or module into smaller, more focused units of functionality, each with a single responsibility. This helps to improve the modularity, maintainability, and extensibility of the code.