Question

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?

Was it helpful?

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();

OTHER TIPS

You can use an extension method:

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

This will allow you to use it just like it was part of the Rectangle struct:

Point rightPoint = rect.RightPoint();

If you want to add a method to an existing class your options are:

  1. Write an extension method for the Rectangle class.
  2. Inherit from the Rectangle class, and add your method to the child class.
  3. Add the member directly to the Rectangle class.

Option #2 requires creating a new type and Option #3 requires you to change the class. I would recommend an extension method like so:

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

This will allow you do make the call you wanted:

var rectangle = new Rectangle();
var point = rectangle.RightPoint();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top