6.5 Type checking and casting
Before a shape can be added to a surface, you can first check whether it fits within the surface. To simplify, we only look at the size of the shape here, not its position.
A circle fits in a rectangular surface if the radius is less than or equal to half the width.
A rectangle fits in a rectangular surface if both the length and width of the rectangle are less than or equal to the length and width of the surface.
-
Add the following method to the
Surfaceclass:1 2 3 4 5 6 7 8 9 10 11 12 13 14
private bool ShapeFitsInSurface(Shape shape) { if (shape is Rectangle rect) { if (rect.Length <= _length && rect.Width <= _width) return true; } else if (shape is Circle circle) { if (circle.Radius <= _width / 2) return true; } return false; }- The condition
shape is Rectangle rectis true if the variableshapeis of the derived classRectangle. The pattern creates a variablerectof typeRectangle. - It is then possible to use
rectin the following lines without explicit casting. - If
shapeis not of typeRectangle, it is treated asCircleand we can use thecirclevariable.
- The condition
-
Add a check in the
AddShape()method:1 2 3 4 5 6 7 8 9 10 11 12
public void AddShape(Shape shape) { if (ShapeFitsInSurface(shape)) { MyShapes.Add(shape); Console.WriteLine("This shape has been added"); } else { Console.WriteLine("This shape is too large"); } } -
Modify the code in your
Mainmethod to test some shapes:1 2 3 4 5 6 7
Surface surface2 = new Surface(10, 7); surface2.AddShape(new Rectangle(4, 3, new Point(0, 7), "red")); surface2.AddShape(new Circle(4, new Point(1.5, 1.5), "yellow")); surface2.AddShape(new Rectangle(9, 8, new Point(3, 2), "green")); surface2.AddShape(new Rectangle(4, 1, new Point(5, 7), "orange")); surface2.AddShape(new Circle(2, new Point(8, 5), "purple")); surface2.AddShape(new Rectangle(11, 3, new Point(5, 3), "blue")); -
Run your program. Your output will look like this:
1 2 3 4 5 6
This shape has been added This shape is too large This shape is too large This shape has been added This shape has been added This shape is too large