3.7. Indirectly Overloading the +=, -=, /=, and *= Operators

Problem

You need to control the handling of the +=, -=, /=, and *= operators within your data type; unfortunately, these operators cannot be directly overloaded.

Solution

Overload these operators indirectly by overloading the +, -, /, and * operators:

public class Foo { // Other class members... // Overloaded binary operators public static Foo operator +(Foo f1, Foo f2) { Foo result = new Foo( ); // Add f1 and f2 here... // Place result of the addition into the result variable return (result); } public static Foo operator +(int constant, Foo f1) { Foo result = new Foo( ); // Add the constant integer and f1 here... // Place result of the addition into the result variable return (result); } public static Foo operator +(Foo f1, int constant) { Foo result = new Foo( ); // Add the constant integer and f1 here... // Place result of the addition into the result variable return (result); } public static Foo operator -(Foo f1, Foo f2) { Foo result = new Foo( ); // Subtract f1 and f2 here... // Place result of the subtraction into the result variable return (result); } public static Foo operator -(int constant, Foo f1) { Foo result = new Foo( ); // Subtract the constant integer and f1 here... // Place result of the subtraction into the result variable return (result); } public static Foo operator -(Foo f1, int constant) { Foo result = new Foo( ); // Subtract the constant integer and f1 here... // Place result of the subtraction ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.