Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata