## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 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 ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required