Skip to content

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.

  1. Add the following method to the Surface class:

     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 rect is true if the variable shape is of the derived class Rectangle. The pattern creates a variable rect of type Rectangle.
    • It is then possible to use rect in the following lines without explicit casting.
    • If shape is not of type Rectangle, it is treated as Circle and we can use the circle variable.
  2. 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");
        }
    }
    
  3. Modify the code in your Main method 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"));
    
  4. 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