Language: EN

csharp-operadores-asignacion

Assignment Operators in C#

Assignment operators in C# 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 assignment, simplifying and optimizing the code.

Basic assignment operator (=)

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

Do not confuse the assignment operator = with the equality comparator ==

Compound assignment operators

Add and assign (+=)

The += operator adds a value to a variable and assigns the result to that variable. For example:

int a = 5;
a += 3; // a is now 8 (equivalent to a = a + 3)

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, the expressions on the right side of the assignment operators are evaluated first.

int a = 5;
int b = 10;
a += b * 2; // a is now 25 (b * 2 is evaluated first, then a += 20)