Recipe 3.7. Indirectly Overloading the +=, -=, /=, and *= OperatorsProblemYou need to control the handling of the +=, -=, /=, and *= operators within your data type; unfortunately, these operators cannot be directly overloaded. SolutionOverload these operators indirectly by overloading the +, -, /, and * operators, as demonstrated in Example 3-9. Example 3-9. Overloading the +, -, /, and * operators
DiscussionWhile it is illegal to overload the +=, -=, /=, and *= operators directly, you can overload them indirectly by overloading the +, -, /, and * operators. The +=, -=, /=, and *= operators use the overloaded +, -, /, and * operators for their calculations. The four operators +, -, /, and * are overloaded by the methods in the Solution section of this recipe. You might notice that each operator is overloaded three times. This is intentional, since a user of your object may attempt to add, subtract, multiply, or divide it by an integer value. The unknown here is: which position will the integer constant be in? Will it be in the first parameter or the second? The following code snippet shows how this might look for multiplication: Foo x = new Foo( ); Foo y = new Foo( ); y *= 100; // Uses: operator *(Foo f1, int multiplier) y = 100 * x; // Uses: operator *(int multiplier, Foo f1) y *= x; // Uses: operator *(Foo f1, Foo f2) The same holds true for the other overloaded operators. If these operators were being implemented in a class, you would first check whether any were set to null. The following code for the overloaded addition operator has been modified to do this: public static Foo operator +(Foo f1, Foo f2) { if (f1 == null) { throw (new ArgumentNullException("f1")); } else if (f2 == null) { throw (new ArgumentNullException("f2")); } else { Foo result = new Foo( ); // Add f1 and f2 here… // place result of the addition into the result variable. return (result); } } See AlsoSee the "Operator Overloading Usage Guidelines," "Overloadable Operators," and "Operator Overloading Tutorial" topics in the MSDN documentation. |