Free mag vol1 | Page 470

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES // Now let's overload the == and != operators. public static bool operator ==(Point p1, Point p2) { return p1.Equals(p2); } } public static bool operator !=(Point p1, Point p2) { return !p1.Equals(p2); } Notice how the implementation of operator == and operator != simply makes a call to the overridden Equals() method to get the bulk of the work done. Given this, you can now exercise your Point class as follows: // Make use of the overloaded equality operators. static void Main(string[] args) { ... Console.WriteLine("ptOne == ptTwo : {0}", ptOne == ptTwo); Console.WriteLine("ptOne != ptTwo : {0}", ptOne != ptTwo); Console.ReadLine(); } As you can see, it is quite intuitive to compare two objects using the well-known == and != operators, rather than making a call to Object. Equals(). If you do overload the equality operators for a given class, keep in mind that C# demands that if you override the == operator, you must also override the != operator (if you forget, the compiler will let you know). Overloading Comparison Operators In Chapter 8, you learned how to implement the IComparable interface in order to compare the relationship between two like objects. You can, in fact, also overload the comparison operators (<, >, <=, and >=) for the same class. As with the equality operators, C# demands that if you overload <, you must also overload >. The same holds true for the <= and >= operators. If the Point type overloaded these comparison operators, the object user could now compare Points, as follows: // Using the overloaded < and > operators. static void Main(string[] args) { ... Console.WriteLine("ptOne < ptTwo : {0}", ptOne < ptTwo); Console.WriteLine("ptOne > ptTwo : {0}", ptOne > ptTwo); Console.ReadLine(); } Assuming you have implemented the IComparable interface (or better yet, the generic equivalent), overloading the comparison operators is trivial. Here is the updated class definition: // Point is also comparable using the comparison operators. public class Point : IComparable { 410