Skip to content

4.6 The ToString method

  1. Add a ToString() method to the Shape class:

    1
    2
    3
    4
    5
    public override string ToString()
    {
        return "Color: " + _color + "\nPerimeter: " + CalculatePerimeter() +
        "\nArea: " + CalculateArea();
    }
    
  2. Add a ToString() method to the Point class:

    1
    2
    3
    4
    public override string ToString()
    {
        return $"({X:F2}, {Y:F2})";
    }
    
  3. Add a ToString() method to the Circle class:

    1
    2
    3
    4
    5
    public override string ToString()
    {
        return base.ToString() + "\nRadius: " + _radius + "\nCenter: " +
        _center.ToString();
    }
    

    base.ToString() calls the ToString() method in the base class Shape. This returns a string as determined in step 1. The Circle class's own attributes are then added. Finally, the ToString() method of the Center point is called.

  4. Add a ToString() method to the Rectangle class:

    1
    2
    3
    4
    5
    public override string ToString()
    {
        return base.ToString() + "\nLength: " + _length + "\nWidth: " +
        _width + "\nCorner: " + _topLeftCorner.ToString();
    }
    
  5. Replace the two for-loops in your Main method 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());
    }
    
  6. Run your program.