Free mag vol1 | Page 467

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES // Overloaded operator +. public static Point operator + (Point p1, Point p2) { return new Point(p1.X + p2.X, p1.Y + p2.Y); } // Overloaded operator -. public static Point operator - (Point p1, Point p2) { return new Point(p1.X - p2.X, p1.Y - p2.Y); } } The logic behind operator + is simply to return a brand-new Point object based on the summation of the fields of the incoming Point parameters. Thus, when you write pt1 + pt2, under the hood you can envision the following hidden call to the static operator + method: // Pseudo-code: Point p3 = Point.operator+ (p1, p2) Point p3 = p1 + p2; Likewise, p1 – p2 maps to the following: // Pseudo-code: Point p4 = Point.operator- (p1, p2) Point p4 = p1 - p2; With this update, our program now compiles, and we find we are able to add and subtract Point objects, as seen in the following output: ptOne ptTwo ptOne ptOne = = + - [100, 100] [40, 40] ptTwo: [140, 140] ptTwo: [60, 60] When you are overloading a binary operator, you are not required to pass in two parameters of the same type. If it makes sense to do so, one of the arguments can differ. For example, here is an overloaded operator + that allows the caller to obtain a new Point that is based on a numerical adjustment: public class Point { ... public static Point operator + (Point p1, int change) { return new Point(p1.X + change, p1.Y + change); } } public static Point operator + (int change, Point p1) { return new Point(p1.X + change, p1.Y + change); } 407