7.2 IComparable interface
- If needed, start from the project up to chapter 6. This contains the classes as you left them at the end of chapter 6.
-
Make the
Shapeclass implement theIComparable<Shape>interface:1public abstract class Shape : IComparable<Shape> -
Add a
CompareTomethod: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; } -
Change the
ToString()method in theSurfaceclass 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. -
Change the code in your
Mainmethod 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); -
Run your program and note that the shapes are displayed in ascending order by area.