2

Possible Duplicate:
Simple way to overload compound assignment operator in C#?

I was playing around with events and thought events are weird. Why couldnt i just implement them in a generic class. So i tried to and found that i CANT OVERLOAD +=. From the language specs found here

The overloadable unary operators are:    
+   -   !   ~   ++   --   true   false

The overloadable binary operators are:    
+   -   *   /   %   &   |   ^   <<   >>   ==   !=   >   <   >=   <=

+= is not listed. Now, before you say theres no reason to overload += i'd like to bring up the fact C# has events which uses the += operator and the fact i tried to implement an event for fun and wanted to use the += operator. Now, i have a feeling someone will say thats why events exist, because it is the only reason. However i want to bring up you can use += with the TimeSpan struct. Go try it, var ts= new TimeSpan(); ts += ts; will compile and run.

I looked at TimeSpan definition and i have no idea how it is allowing it. I saw a public static TimeSpan operator +(TimeSpan t); which looked suspicious but then i realize its for something like var name = +ts; like how you can do var name = -ts; for negation.

So my question is, how do i use the += for my struct or class. It appears to be supported i just cant seem to find the documentation on it.

Community
  • 1
  • 1

4 Answers4

16

Events don't overload the += and -= operator. This is just hardcoded in the C# compiler which translates it into the add/remove methods of that event.

You can only overload + and - which then indirectly overload += and -=. If you overload + then automatically x += y becomes overloaded to x = x + y. So for your type you don't need to put in any extra work. Just overload + and you'll get += for free. This of course requires the left side argument and the result type being compatible, but that's usually the case.


The reason that you can't overload += separately is most likely that it creates strange semantics for reference types. If += modified the existing instance of the left side then the following code would behave strangely:

MyClass x=new MyClass();
MyClass y=x;
x+=SomeThing;
y has changed now too

On the other hand with += meaning x = x+y this code creates a new instance which it assigns to x. And the original instance remains unmodified in y;


In C++ on the other hand it is possible to safely specify a separate overload for += because you can overload the assignment and copy-constructor at the same time and use that to get the correct semantics.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • Great answer you explain exactly why += cant be overloaded and gave me reasoning that actually make sense! –  Mar 05 '11 at 09:39
  • Maybe you know the answer to this as well? http://stackoverflow.com/questions/5203093 –  Mar 05 '11 at 10:16
  • 1
    Overloading `+=` separately could create strange semantics, but it would also allow a type to perform the read and write-back in thread-safe manner [e.g. `event += someDelegate`; is implemented in thread-safe fashion, and one could code `void myThing.AddTo(ref myThing dest, myThing src);` so as to make `myThing.AddTo(ref someSharedField, someData)` safe, but `someSharedField = someSharedField + someData;` cannot be made intrinsically thread-safe. Without being able to map `+=` to a method that takes a `ref` parameter, it cannot be used in inherently thread-safe fashion except for events. – supercat Apr 03 '13 at 17:25
1

The += operator cannot be overloaded directly, but user-defined types can overload the + operator.

An expression using the += assignment operator, such as Copy

x += y

is equivalent to Copy

x = x + y

Msdn

Community
  • 1
  • 1
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
0

+= is just a shorthand for addition, then assignment. You can overload the + operator, which also makes the += operator work:

This compiles

class P 
{
    public static P operator +(P rhs, P lhs) {
        return null;
    }   
}

void Main()
{
    P p = new P();
    p += new P();
}

(And, vice versa for - and -= operators, of course).

driis
  • 161,458
  • 45
  • 265
  • 341
0

The documentation doesn't lie. It's not possible to overload the += operator.

The += operator is just a shortcut for using the + operator. An operation like x += y is translated into x = x + y by the compiler.

So, to change what the += operator does, you have to overload the + operator.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005