Free mag vol1 | Page 471

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES ... public int CompareTo(Point other) { if (this.X > other.X && this.Y > other.Y) return 1; if (this.X < other.X && this.Y < other.Y) return -1; else return 0; } public static bool operator <(Point p1, Point p2) { return (p1.CompareTo(p2) < 0); } public static bool operator >(Point p1, Point p2) { return (p1.CompareTo(p2) > 0); } public static bool operator <=(Point p1, Point p2) { return (p1.CompareTo(p2) <= 0); } public static bool operator >=(Point p1, Point p2) { return (p1.CompareTo(p2) >= 0); } } Final Thoughts Regarding Operator Overloading As you have seen, C# provides the capability to build types that can respond uniquely to various intrinsic, well-known operators. Now, before you go and retrofit all your classes to support such behavior, you must be sure that the operator(s) you are about to overload make some sort of logical sense in the world at large. For example, let’s say you overloaded the multiplication operator for the MiniVan class. What exactly would it mean to multiply two MiniVan objects? Not much. In fact, it would be very confusing for teammates to see the following use of MiniVan objects: // Huh?! This is far from intuitive... MiniVan newVan = myVan * yourVan; Overloading operators is generally useful only when you’re building atomic data types. Text, points, rectangles, fractions, and hexagons make good candidates for operator overloading. People, managers, cars, database connections, and web pages do not. As a rule of thumb, if an overloaded operator makes it harder for the user to understand a type’s functionality, don’t do it. Use this feature wisely.  Source Code The OverloadedOps project is located under the Chapter 11 subdirectory. 411