views:

351

answers:

4
+1  Q: 

meaning of '+='

I'm confused with the syntax of C#: what is the use of "+="?

+5  A: 
a += 3

is the same as

a = a + 3
Extrakun
+27  A: 

The += syntax can be used in different ways:

SomeEvent += EventHandler;

Adds a handler to an event.


SomeVariable += 3;

Is equivalent to

SomeVariable = SomeVariable + 3;
SLaks
Good answer. I would have spaced on the event handler aspect of this operator, despite knowing better.
Beska
The event handler aspect is pretty much identical to the other aspects; all that's happening there is that the event/delegate object overrides the + operator.a += b is simply syntactic sugar for a = a + b. See http://msdn.microsoft.com/en-us/library/8edha89s.aspx, which states "Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded."
technophile
@Technophile: Wrong. When outside the class (or always in C# 4.0), `instance.Event += handler` compiles to `instance.add_Event(handler);`
SLaks
@SLaks Thank you for the clarification. They're conceptually identical, I had just misremembered the implementation.
technophile
@Technophile: They're not entirely conceptually identical. In fact, it's a (subtle) breaking change: http://blogs.msdn.com/cburrows/archive/2010/03/18/events-get-a-little-overhaul-in-c-4-part-iii-breaking-changes.aspx
SLaks
On an event, it calls the add method associated with the event. On a delegate field, however, it decomposed to SomeDelegate = SomeDelegate + AnotherDelegate and just concatenates the invocation lists.
Ben Voigt
+4  A: 

This is called a compound operator. There common to all languages I can thing of - Javascript, C, Java, PHP, .net, GL etc.

Like everyone has said, is a shorten'd version of value = value + 3.

There are multiple reasons for its use. Most obviously its quicker to write, easier to read and faster to spot errors with.

Most importantly, a compound operator is specifically designed not to require as must computation as the equivalent value = value + 3 I'm not totally sure why but the evidence is paramount.

Simply create a loop, looping for say 5,000,000 adding a value as you proceed. In two test cases, I know personally from Actionscript there is roughly an 60% speed increase with compound operators.


You also have the equivalent:

+= addition

-= subtraction

/= multiplication

*= multplication

%= modulus

and the lesser obvious

++ Plus one

-- Minus one


Hope it helps buddy.

Glycerine
A: 

note it is not necessarily always equivalent.

for ordinary variables, a+=a is, indeed, equivalent to a=a+a (and shorter!). for the odd variable which changes its state, not so much.

sreservoir