What does the /= operator in C# do and when is it used?
It's divide-and-assign. x /= n
is logically equivalent to x = x / n
.
It is similar to +=
, -=
or *=
. It's a shortcut for a mathematical division operation with an assignment. Instead of doing
x = x / 10;
You can get the same result by doing
x /= 10;
It assigns the result to the original variable after the operation has taken place.
A division and an assignment:
a /= b;
is the same as
a = (a / b);
Its simply a combination of the two operators into one.
In the following example:
double value = 10;
value /= 2;
Value will have a final value of 5.
The =/ operator divides the variable by the operand (in this case, 2) and stores the result back in the variable.
In most languages inspired by C, the answer is: divide and assign. That is:
a /= b;
is a short-hand for:
a = a / b;
The LHS (a
in my example) is evaluated once. This matters when the LHS is complex, such as an element from an array of structures:
x[i].pqr /= 3;