Assignment operators allow us to assign values to variables.
The most common assignment operator is the =
operator. This operator is used to assign the value on the right to the variable on the left.
In addition to the basic assignment operator (=), there are compound assignment operators that combine an arithmetic operation with the assignment, simplifying and optimizing the code.
Assignment operators in C# include:
- = (Assignment): Assigns a value to a variable.
- += (Add and Assign): Adds the value to the variable and assigns the result to the variable.
- -= (Subtract and Assign): Subtracts the value from the variable and assigns the result to the variable.
- *= (Multiply and Assign): Multiplies the value of the variable and assigns the result to the variable.
- /= (Divide and Assign): Divides the value of the variable and assigns the result to the variable.
- %= (Modulo and Assign): Calculates the modulo of the value of the variable and assigns the result to the variable.
Do not confuse the assignment operator =
with the equality operator ==
:::
List of assignment operators
Assignment (=)
The basic assignment operator (=
) is used to assign a value to a variable. For example:
int a = 5; // Assigns the value 5 to variable a
The assignment operator is also used to update the value of a variable. For example:
int a = 5; // Initial assignment
a = 10; // Value update
Subtract and Assign (-=)
The -=
operator subtracts a value from a variable and assigns the result to that variable. For example:
int a = 10;
a -= 3; // a is now 7 (equivalent to a = a - 3)
Multiply and Assign (*=)
The *=
operator multiplies a variable by a value and assigns the result to that variable. For example:
int a = 4;
a *= 6; // a is now 24 (equivalent to a = a * 6)
Divide and Assign (/=)
The /=
operator divides a variable by a value and assigns the result to that variable. For example:
int a = 20;
a /= 4; // a is now 5 (equivalent to a = a / 4)
Modulo and Assign (%=)
The %=
operator calculates the modulo of a variable by a value and assigns the result to that variable. For example:
int a = 17;
a %= 5; // a is now 2 (equivalent to a = a % 5)
Operator precedence
It is important to remember that assignment operators have a lower precedence than most other operators in C#. Therefore, expressions on the right side of assignment operators are evaluated first.
For example:
int a = 5;
int b = 10;
a += b * 2; // a is now 25 (b * 2 is evaluated first, then a += 20)