How to check if a point is inside a rectangle in C#

1 Answer

0 votes
using System;

class Program
{
    struct Point {
        public double X, Y;

        public Point(double x, double y) {
            X = x;
            Y = y;
        }
    }

    struct Rectangle {
        public Point TopLeft;
        public Point BottomRight;

        public Rectangle(Point topLeft, Point bottomRight) {
            TopLeft = topLeft;
            BottomRight = bottomRight;
        }
    }

    static bool IsPointInsideRectangle(Point p, Rectangle rect) {
        return p.X >= rect.TopLeft.X && p.X <= rect.BottomRight.X &&
               p.Y >= rect.TopLeft.Y && p.Y <= rect.BottomRight.Y;
    }

    static void Main()
    {
        Rectangle rect = new Rectangle(new Point(0.0, 0.0), new Point(7.0, 7.0));
        Point p = new Point(3.0, 2.0);

        if (IsPointInsideRectangle(p, rect)) {
            Console.WriteLine("The point is inside the rectangle.");
        }
        else {
            Console.WriteLine("The point is outside the rectangle.");
        }
    }
}


  
/*
run:
  
The point is inside the rectangle.
  
*/

 



answered Jun 22, 2025 by avibootz
...