Alex
Alex

Reputation: 77359

What does the /= operator in C# do?

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

Upvotes: 8

Views: 2527

Answers (7)

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

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;

Upvotes: 4

Christian Merat
Christian Merat

Reputation: 4314

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.

Upvotes: 2

Joseph
Joseph

Reputation: 25523

a /= b;

is the same as

a = a / b;

Here's the msdn article on the operator.

Upvotes: 1

LorenVS
LorenVS

Reputation: 12867

A division and an assignment:

a /= b;

is the same as

a = (a / b);

Its simply a combination of the two operators into one.

Upvotes: 2

Havenard
Havenard

Reputation: 27914

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

Upvotes: 2

womp
womp

Reputation: 116987

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.

Upvotes: 7

chaos
chaos

Reputation: 124345

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

Upvotes: 28

Related Questions