CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
// Just a simple, everyday C# class.
public class Point
{
public int X {get; set;}
public int Y {get; set;}
public Point(int xPos, int yPos)
{
X = xPos;
Y = yPos;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", this.X, this.Y);
}
}
Now, logically speaking, it makes sense to “add” Points together. For example, if you added together
two Point variables, you should receive a new Point that is the summation of the X and Y values. Of
course, it might also be helpful to subtract one Point from another. Ideally, you would like to be able to
author the following code:
// Adding and subtracting two points?
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Overloaded Operators *****\n");
// Make two points.
Point ptOne = new Point(100, 100);
Point ptTwo = new Point(40, 40);
Console.WriteLine("ptOne = {0}", ptOne);
Console.WriteLine("ptTwo = {0}", ptTwo);
// Add the points to make a bigger point?
Console.WriteLine("ptOne + ptTwo: {0} ", ptOne + ptTwo);
}
// Subtract the points to make a smaller point?
Console.WriteLine("ptOne - ptTwo: {0} ", ptOne - ptTwo);
Console.ReadLine();
However, as our Point now stands, we will receive compile-time errors, as the Point type does not
know how to respond to the + or - operators. To equip a custom type to respond uniquely to intrinsic
operators, C# provides the operator keyword, which you can use only in conjunction with the static
keyword. When you overload a binary operator (such as + and -), you will most often pass in two
arguments that are the same type as the defining class (a Point in this example), as illustrated in the
following code update:
// A more intelligent Point type.
public class Point
{
...
406