Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

meaning of '+='

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

like image 763
Amal Avatar asked Nov 26 '22 23:11

Amal


2 Answers

The += syntax can be used in different ways:

SomeEvent += EventHandler;

Adds a handler to an event.


SomeVariable += 3;

Is equivalent to

SomeVariable = SomeVariable + 3;
like image 154
SLaks Avatar answered Nov 29 '22 11:11

SLaks


This is called a compound operator. They are common to all languages I can thing of: Javascript, C, Java, PHP, .net, GL.

Like everyone has said, is a shortened version of value = value + 3.

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

Most importantly, a compound operator is specifically designed not to require as much 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 a 60% speed increase with compound operators.


You also have the equivalent:

+=: addition

-=: subtraction

/=: multiplication

*=: multplication

%=: modulus

and the less obvious:

++: Plus one

--: Minus one

like image 26
Glycerine Avatar answered Nov 29 '22 11:11

Glycerine