SOLIDOpenClosedPrinciple

CSharp · Console

/Program.cs

using System;

namespace Problem 
{
	internal interface IShape
	{
		void Render();
	}
	internal class Circle : IShape
	{
		public double Radius { get; init; }

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

		public void Render()
		{
			Console.WriteLine("Rendering circle");
		}
	}
	internal class Rectangle : IShape
	{
		public double Width { get; init; }

		public double Height { get; init; }

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

		public void Render()
		{
			Console.WriteLine("Rendering rectangle");
		}
	}
	internal class ShapeCalculator
	{
		public void CalculateArea(IShape shape)
		{
			if(shape is Circle circle)
			{
				Console.WriteLine(3.14 * circle.Radius * circle.Radius);
			}
			else if(shape is Rectangle rect)
			{
				Console.WriteLine(rect.Width * rect.Height);
			}
		}
	}
}

namespace Solution 
{
	internal interface IShape
	{
		void Render();
		void CalculateArea();
	}
	internal class Circle : IShape
	{
		public double Radius { get; init; }

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

		public void Render()
		{
			Console.WriteLine("Rendering circle");
		}

		public void CalculateArea()
		{
			Console.WriteLine(3.14 * this.Radius * this.Radius);
		}
	}
	internal class Rectangle : IShape
	{
		public double Width { get; init; }

		public double Height { get; init; }

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

		public void Render()
		{
			Console.WriteLine("Rendering rectangle");
		}

		public void CalculateArea()
		{
			Console.WriteLine(this.Width * this.Height);
		}
	}
	internal class ShapeCalculator
	{
		public void CalculateArea(IShape shape)
		{
			shape.CalculateArea();
		}
	}

}
					
public class Program
{
	public static void Main()
	{
		var circle = new Solution.Circle(10);
        var shapeCalculator = new Solution.ShapeCalculator();
        shapeCalculator.CalculateArea(circle);
	}
}
;