
.NET 1.1+C# Basic Operator Overloading (2)
The eighth article in the C# Object-Oriented Programming tutorial describes a third overloading technique. By overloading the functionality of operators, the operation of the standard operators including + and - can be defined for new classes.
Creating the Addition (+) Operator
The syntax for binary operators can now be used to create a new addition operator for the Vector class. This operator will simply add the X and Y elements of two vectors together and return a new vector containing the result. Add the following to the Vector class to provide this functionality. Note that a new Vector is created rather than adjusting one of the operands. This is because the operands are reference-types and the original values should not be updated in this case.
public static Vector operator +(Vector v1, Vector v2)
{
return new Vector(v1.X + v2.X, v1.Y + v2.Y);
}
We can now test the Vector's new operator by modifying the program's main method. The following program instantiates two Vector objects, adds them together and outputs the values of the resultant Vector's X and Y properties.
static void Main(string[] args)
{
Vector v1 = new Vector(4, 11);
Vector v2 = new Vector(0, 8);
Vector v3 = v1 + v2;
Console.WriteLine("({0},{1})", v3.X, v3.Y); // Outputs "(4,19)"
}
Creating the Subtraction (-) Operator
Addition is a commutative operation. This means the order of the two operands can be swapped without affecting the outcome. In the case of subtraction this is not the case so it important to remember that the first operand in the declaration represents the value to the left of the operator and the second operand represents the value to the right. If these are used incorrectly, the resultant value will be incorrect. Using this knowledge we can add a subtraction operator to the Vector class:
public static Vector operator -(Vector v1, Vector v2)
{
return new Vector(v1.X - v2.X, v1.Y - v2.Y);
}
To test the new operator, modify the Main method as follows and execute the program.
static void Main(string[] args)
{
Vector v1 = new Vector(4, 11);
Vector v2 = new Vector(0, 8);
Vector v3 = v1 - v2;
Console.WriteLine("({0},{1})", v3.X, v3.Y); // Outputs "(4,3)"
}
10 November 2007