Reputation: 367
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
Upvotes: 0
Views: 109
Reputation: 3345
You need to instantiate instances of each shape and pass those as an array to the AreaCalculator.Area()
method. The key take away is the Area
method will take any objects that extend Shape
.
var circle = new Circle();
circle.Radius = 5;
var rectangle = new Rectangle();
rectangle.Width = 10;
rectangle.Height = 3;
var area = AreaCalculator.Area(new Shape[] {circle, rectangle});
Or more succinctly
AreaCalculator.Area(new Shape[]{
new Circle() {Radius = 5},
new Rectangle() {Width = 10, Height = 3}
});
Upvotes: 1
Reputation: 20353
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();
Upvotes: 2