Skip to content

7.2 IComparable interface

  1. If needed, start from the project up to chapter 6. This contains the classes as you left them at the end of chapter 6.
  2. Make the Shape class implement the IComparable<Shape> interface:

    1
    public abstract class Shape : IComparable<Shape>
    
  3. Add a CompareTo method:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    public int CompareTo(Shape? other)
    {
        if (other == null) return 1;
        if (CalculateArea() > other.CalculateArea())
            return 1;
        else if (CalculateArea() < other.CalculateArea())
            return -1;
        else
            return 0;
    }
    
  4. Change the ToString() method in the Surface class as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    public override string ToString()
    {
        string result = "";
        if (MyShapes.Count > 0)
        {
            MyShapes.Sort();
            foreach (Shape shape in MyShapes)
            {
                result += shape.ToString() + "\n\n";
            }
        }
        return result;
    }
    

    Note that MyShapes.Sort() sorts the list first. The items are then printed in ascending order by area.

  5. Change the code in your Main method as follows:

    1
    2
    3
    4
    5
    6
    7
    8
    Surface surface = new Surface(10, 7);
    surface.AddShape(new Rectangle(3, 3, new Point(0, 7), "red"));
    surface.AddShape(new Rectangle(3, 2, new Point(0, 4), "yellow"));
    surface.AddShape(new Rectangle(5, 2, new Point(0, 2), "green"));
    surface.AddShape(new Rectangle(2, 5, new Point(3, 7), "purple"));
    surface.AddShape(new Rectangle(5, 4, new Point(5, 7), "orange"));
    surface.AddShape(new Rectangle(5, 3, new Point(5, 3), "blue"));
    Console.WriteLine(surface);
    
  6. Run your program and note that the shapes are displayed in ascending order by area.