C# Assignment Operators

Assignment operators are used to assign values to variables. The basic assignment operator is the = operator, but C# also provides compound assignment operators for performing arithmetic operations and assignment in one step.

Key Topics

Basic Assignment Operator (=)

The = operator assigns the value on the right-hand side to the variable on the left-hand side.

Example: Basic Assignment

int a = 5;  // Assign 5 to variable a
string name = "John";  // Assign "John" to variable name
Console.WriteLine($"a = {a}, Name = {name}");

Output:

a = 5, Name = John

Add and Assign (+=)

The += operator adds the right-hand value to the left-hand variable and then assigns the result to the left-hand variable.

Example: Add and Assign

int x = 10;
x += 5;  // x = x + 5
Console.WriteLine($"x = {x}");

Output:

x = 15

Subtract and Assign (-=)

The -= operator subtracts the right-hand value from the left-hand variable and then assigns the result to the left-hand variable.

Example: Subtract and Assign

int y = 20;
y -= 3;  // y = y - 3
Console.WriteLine($"y = {y}");

Output:

y = 17

Multiply and Assign (*=)

The *= operator multiplies the left-hand variable by the right-hand value and then assigns the result to the left-hand variable.

Example: Multiply and Assign

int z = 7;
z *= 2;  // z = z * 2
Console.WriteLine($"z = {z}");

Output:

z = 14

Divide and Assign (/=)

The /= operator divides the left-hand variable by the right-hand value and then assigns the result to the left-hand variable.

Example: Divide and Assign

int a = 20;
a /= 4;  // a = a / 4
Console.WriteLine($"a = {a}");

Output:

a = 5

Key Takeaways

  • =: Assigns the right-hand value to the left-hand variable.
  • +=: Adds the right-hand value to the left-hand variable.
  • -=: Subtracts the right-hand value from the left-hand variable.
  • *=: Multiplies the left-hand variable by the right-hand value.
  • /=: Divides the left-hand variable by the right-hand value.