views:

430

answers:

8

What does the /= operator in C# do and when is it used?

+28  A: 

It's divide-and-assign. x /= n is logically equivalent to x = x / n.

chaos
+1. thats a better way to put than my pityful attempt ;)
AnthonyWJones
... except that `x` is only evaluated once (which is observable if it is an expression with side effects - e.g., a chain of property gets).
Pavel Minaev
Excellent illustration of the difference between logical equivalence and practical equivalence. :)
chaos
+7  A: 

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.

womp
@AsmodonYou are wrong. Both of womps lines are equivalent. And they both modify the value of x (the same way). AND it is shorter, if only by an 'x' and a space ;)
galaktor
+2  A: 

a /= 2; is the same of a = a / 2;.

Havenard
Beaten by 14 secs
Rowland Shaw
+2  A: 

A division and an assignment:

a /= b;

is the same as

a = (a / b);

Its simply a combination of the two operators into one.

LorenVS
+1  A: 
a /= b;

is the same as

a = a / b;

Here's the msdn article on the operator.

Joseph
A: 

int i = 4; int j = i / 2; j /= 2;

den123
+2  A: 

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.

CMerat
+4  A: 

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;
Jonathan Leffler