Free mag vol1 | Page 468

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES Notice that you need both versions of the method if you want the arguments to be passed in either order (i.e., you can’t just define one of the methods and expect the compiler to automatically support the other one). We are now able to use these new versions of operator + as follows: // Prints [110, 110]. Point biggerPoint = ptOne + 10; Console.WriteLine("ptOne + 10 = {0}", biggerPoint); // Prints [120, 120]. Console.WriteLine("10 + biggerPoint = {0}", 10 + biggerPoint); Console.WriteLine(); And What of the += and –+ Operators? If you are coming to C# from a C++ background, you might lament the loss of overloading the shorthand assignment operators (+=, -=, and so forth). Don’t despair. In terms of C#, the shorthand assignment operators are automatically simulated if a type overloads the related binary operator. Thus, given that the Point structure has already overloaded the + and - operators, you can write the following: // Overloading binary operators results in a freebie shorthand operator. static void Main(string[] args) { ... // Freebie += Point ptThree = new Point(90, 5); Console.WriteLine("ptThree = {0}", ptThree); Console.WriteLine("ptThree += ptTwo: {0}", ptThree += ptTwo); // Freebie -= Point ptFour = new Point(0, 500); Console.WriteLine("ptFour = {0}", ptFour); Console.WriteLine("ptFour -= ptThree: {0}", ptFour -= ptThree); Console.ReadLine(); } Overloading Unary Operators C# also allows you to overload various unary operators, such as ++ and --. When you overload a unary operator, you also must use the static keyword with the operator keyword; however, in this case you simply pass in a single parameter that is the same type as the defining class/structure. For example, if you were to update the Point with the following overloaded operators: public class Point { ... // Add 1 to the X/Y values for the incoming Point. public static Point operator ++(Point p1) { return new Point(p1.X+1, p1.Y+1); } 408