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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With