I was working out sample code of Windows phone and often I see statements with +=
operator.
I know about add assignment operator which does the below operation
+= means a = a + b; // used for both adding number and string concatenation
But this is new to me
phNumChoseTask = new PhoneNumberChooserTask();
phNumChoseTask.Completed += new EventHandler<PhoneNumberResult>(phoneNumberChooserTask_Completed);
Here how does +=
works?
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A. -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand.
The plus equal operator += in JavaScript is a shorthand operator that allows you to add the value from the right operand to the left operand. For example, you can add 3 to the num like this: let num = 7; num += 3; console.
The Python += operator adds two values together and assigns the final value to a variable. This operator is called the addition assignment operator.
In the current context +=
means subscribe
. In other words it's like you are telling subscribe my method (the right operand) to this event (the left operand)
, this way, when the event is raised, your method will be called. Also, it is a good practice to unsubscribe
(-=
from this event, when you have finished your work ( but before you dispose you object ) in order to prevent your method being called and to prevent resource leaks. FMI look here.
The += operator is used to specify a method that will be called in response to an event; such methods are called event handlers. The use of the += operator in this context is referred to as subscribing to an event.
Other usage, It can also be used as assignment operator:
a=a+b;
can be written as
a+=b;
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