Interface vs Abstract Class: Shape example

CSharp · Console

/Program.cs

using System;

public interface IShape
{
    double CalculateArea();
}

public interface IComparableShape
{
    int CompareTo(IShape other);
}

public abstract class Shape : IShape
{
    public string Name { get; }

    protected Shape(string name)
    {
        Name = name;
    }

    public abstract double CalculateArea();

    public void PrintInfo()
    {
        Console.WriteLine($"{Name}: area = {CalculateArea():F2}");
    }
}

public class Circle : Shape, IComparableShape
{
    private readonly double _radius;

    public Circle(double radius) : base("Circle")
    {
        _radius = radius;
    }

    public override double CalculateArea() => Math.PI * _radius * _radius;

    public int CompareTo(IShape other) => CalculateArea().CompareTo(other.CalculateArea());
}

public class Rectangle : Shape
{
    private readonly double _width;
    private readonly double _height;

    public Rectangle(double width, double height) : base("Rectangle")
    {
        _width = width;
        _height = height;
    }

    public override double CalculateArea() => _width * _height;
}

public class ShapeReportService
{
    private readonly IShape _shape;

    public ShapeReportService(IShape shape)
    {
        _shape = shape;
    }

    public void Report() => Console.WriteLine($"Report -> area: {_shape.CalculateArea():F2}");
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Abstract class provides shared, concrete behavior (PrintInfo):");
        var circle = new Circle(5);
        var rectangle = new Rectangle(4, 6);
        circle.PrintInfo();
        rectangle.PrintInfo();

        Console.WriteLine();
        Console.WriteLine("Circle also implements a second interface, IComparableShape:");
        Console.WriteLine($"circle.CompareTo(rectangle) = {circle.CompareTo(rectangle)}");

        Console.WriteLine();
        Console.WriteLine("DI-style usage: ShapeReportService depends only on IShape");
        var today = new ShapeReportService(circle);
        today.Report();

        var tomorrow = new ShapeReportService(rectangle);
        tomorrow.Report();
    }
}
;