How to add * operator to Point class?

  • Thread starter Thread starter Norvin Laudon
  • Start date Start date
N

Norvin Laudon

Hi,

How can I add a multiplication operator to an existing class ("Point")?

<i.e.>
Point newPoint = new Point(existingPoint.X * scale, existingPoint.Y *
scale);
</i.e.>

I can't seem to create my own class and inherit from Point, since it is
sealed... (I think it's actually a struct).

I could create my own class, and duplicate all of the behaviour of Point,
but I am using many framework methods in my project which take Point as a
parameter. If I made my own class, I would have to cast to (Point) eveytime
I use a framework method...

Any suggestions?

Norvin
 
I've seen this come up before (somebody wanted methods for Polar
coordinates, and complained because MS made the "poor choice" of "sealing"
Point), and after a bit I came up with a decent solution (similar to the
local extension refactoring method).

Just wrap the Point struct in your own struct, implementing all of Point's
methods and properties, but in turn just calling the Point's members. Then
add any additional methods and operators he wants. Finally, write implicit
conversion operators to and from the Point class. Then the new struct
should be able to be used almost seamlessly with regular points.

for example:

// Name this struct something better than MyPoint :-)
public struct MyPoint {
private Point point;

public MyPoint(Point point) {
this.point = point;
}

// Point wrapper members
public MyPoint(int x, int y) {
point = new Point(x, y);
}
public int X {
get { return point.X; }
}
public int Y {
get { return point.Y; }
}
//etc...... implement Point's other properties, members and operators

// Add any operators or methods you want here
public MyPoint operator* (MyPoint p, int factor) {
return new MyPoint();
}

// Add these implicit conversions so that you can use Point and MyPoint
interchangably
public implicit operator Point(MyPoint p) {
return p.point;
}
public implicit operator MyPoint(Point p) {
return new MyPoint(p);
}

}
 
Matthew,

That's a great solution. I had this idea earlier, but I didn't know about
the 'implicit' conversion keyword. That makes things a whole lot easier,
avoiding ugly casts etc!

Norvin
 
Back
Top