4.6 The ToString method
-
Add a
ToString()method to theShapeclass:1 2 3 4 5
public override string ToString() { return "Color: " + _color + "\nPerimeter: " + CalculatePerimeter() + "\nArea: " + CalculateArea(); } -
Add a
ToString()method to thePointclass:1 2 3 4
public override string ToString() { return $"({X:F2}, {Y:F2})"; } -
Add a
ToString()method to theCircleclass:1 2 3 4 5
public override string ToString() { return base.ToString() + "\nRadius: " + _radius + "\nCenter: " + _center.ToString(); }base.ToString()calls theToString()method in the base classShape. This returns a string as determined in step 1. TheCircleclass's own attributes are then added. Finally, theToString()method of the Center point is called. -
Add a
ToString()method to theRectangleclass:1 2 3 4 5
public override string ToString() { return base.ToString() + "\nLength: " + _length + "\nWidth: " + _width + "\nCorner: " + _topLeftCorner.ToString(); } -
Replace the two for-loops in your
Mainmethod as follows:1 2 3 4 5 6 7 8 9 10 11
for (int i = 0; i < myCircleArray.Length; i++) { Console.WriteLine(myCircleArray[i]); Console.WriteLine(myCircleArray[i].DescribeSize()); } for (int i = 0; i < myRectangleArray.Length; i++) { Console.WriteLine(myRectangleArray[i]); Console.WriteLine(myRectangleArray[i].DescribeSize()); } -
Run your program.