Im following a tutorial based on SOLID principles but i fail to understand how to actually implement this method, here is the tutorial Link
I faily understand the concept of the code but i cant figure out how to actually call the AreaCalculator.Area method from my Main
How do i call the method to either calculate the Rectangle Area or the Circle Area? based on the code in the tutorial
Area(Circle with 10 radius);
Area(Rectangle with 10 width and 5 height);
Shape.cs
public abstract class Shape
{
public abstract double Area();
}
Circle.cs
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area()
{
return Radius * Radius * Math.PI;
}
}
Rectangle.cs
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area()
{
return Width * Height;
}
}
AreaCalculator.cs
public static double Area(Shape[] shapes)
{
double area = 0;
foreach (var shape in shapes)
{
area += shape.Area();
}
return area;
}
Thank you
var circle = new Circle { Radius = 10 }; // Create a circle
var rectangle = new Rectangle { Width = 10, Height = 5 }; // Create a rectangle
var shapes = new Shape[] { circle, rectangle }; // Create array of shapes
double area = AreaCalculator.Area(shapes); // Call Area method with array
If you only need the area of a single shape, the AreaCalculator
is unneccesary; simply call the Area
method on an individual shape:
double circleArea = circle.Area();
double rectangleArea = rectangle.Area();