Search code examples
c#inheritancestaticextendrectangles

Reverse Extending a Class


I am trying to make a class which "reverse" extends Rectangle. I want to be able to put this method in the class:

    public Point RightPoint()
    {
        return new Point(this.X + this.Width, this.Y + this.Height / 2);
    }

and then call rectangle.RightPoint(); and get the return value. (X, Y, Width, and Height are fields of the Rectangle).

Is this possible? Or do I need to make these static methods and then pass them a Rectangle?


Solution

  • I think you need an extension method

    public static Point RightPoint(this Rectangle rectangle)
    {
        return new Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height / 2);
    }
    

    The above code should go inside a static class.

    Then you can do this on a Rectangle object:

    Rectangle rect = new Rectangle();
    Point pointObj = rect.RightPoint();