I have been looking everywhere to figure out what these mean and how they are used +=
, -=
, *=
, /=
, the most I have found is that they are, "Assignment by Addition", "Assignment by Difference", "Assignment by Product", "Assignment by Quotient", etc, but I can't figure out when or how they are used. If anyone can please explain this to me I would be very grateful. thanks
They are shorthand:
a += b
is the same as
a = a + b
Etc...
so
a -= b
is equivalent to a = a - b
a *= b
is equivalent to a = a * b
a /= b
is equivalent to a = a / b
As Kevin Brydon suggested - Familiarize yourself with the operators in C# here.
See 7.13 Assignment operators
in the spec and its subsections., specifically 7.13.2 Compound assignment
:
An operation of the form x op= y is processed by applying binary operator overload resolution (Section 7.2.4) as if the operation was written x op y. Then,
•If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, except that x is evaluated only once.
•Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.
•Otherwise, the compound assignment is invalid, and a compile-time error occurs.
a+=1 means a = a+1
a-=2 means a = a-2
a*=3 means a = a*3
a/=4 means a = a/4
These are Assignment operators(Shorthands)
a += 1; is equal to a = a + 1;
b -= 1; is equal to b = b - 1;
a *= 1; is equal to a = a * 1;
b /= 1; is equal to b = b / 1;
Refer:Link
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