CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
// Subtract 1 from the X/Y values for the incoming Point.
public static Point operator --(Point p1)
{
return new Point(p1.X-1, p1.Y-1);
}
}
you could increment and decrement Point’s x and y values like this:
static void Main(string[] args)
{
...
// Applying the ++ and -- unary operators to a Point.
Point ptFive = new Point(1, 1);
Console.WriteLine("++ptFive = {0}", ++ptFive); // [2, 2]
Console.WriteLine("--ptFive = {0}", --ptFive); // [1, 1]
// Apply same operators as postincrement/decrement.
Point ptSix = new Point(20, 20);
Console.WriteLine("ptSix++ = {0}", ptSix++); // [20, 20]
Console.WriteLine("ptSix-- = {0}", ptSix--); // [21, 21]
Console.ReadLine();
}
Notice in the preceding code example we are applying our custom ++ and -- operators in two
different manners. In C++, it is possible to overload pre- and postincrement/decrement operators
separately. This is not possible in C#. However, the return value of the increment/decrement is
automatically handled “correctly” free of charge (i.e., for an overloaded ++ operator, pt++ has the value of
the unmodified object as its value within an expression, while ++pt has the new value applied before use
in the expression).
Overloading Equality Operators
As you might recall from Chapter 6, System.Object.Equals() can be overridden to perform value-based
(rather than referenced-based) comparisons between reference types. If you choose to override Equals()
(and the often related System.Object.GetHashCode() method), it is trivial to overload the equality
operators (== and !=). To illustrate, here is the updated Point type:
// This incarnation of Point also overloads the == and != operators.
public class Point
{
...
public override bool Equals(object o)
{
return o.ToString() == this.ToString();
}
public override int GetHashCode()
{
return this.ToString().GetHas