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.
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 likex += y
is translated intox = x + y
by the compiler.So, to change what the
+=
operator does, you have to overload the+
operator.+=
is just a shorthand for addition, then assignment. You can overload the+
operator, which also makes the+=
operator work:This compiles
(And, vice versa for
-
and-=
operators, of course).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 automaticallyx += y
becomes overloaded tox = 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:On the other hand with
+=
meaningx = 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.Msdn