C# Assignment Operators

Assignment operators are used to give values to variables. You have already met the most important one, the single equals sign =. But C# also provides compound assignment operators that let you update a variable based on its current value in a shorter, cleaner way.

The basic assignment operator

The = operator takes the value on its right and stores it in the variable on its left. It is important to remember that in C# a single = means assign, not equals. Comparing for equality is done with ==, which you will meet on the next page.

Assigning a value

int score = 10;
score = 20; // score now holds 20
Console.WriteLine(score);

Compound assignment operators

Very often you want to update a variable using its own current value, for example adding points to a running total. Instead of writing score = score + 5, you can use the compound operator += to say the same thing more briefly.

The long way vs the short way

int score = 10;
score = score + 5; // long way, score is 15
score += 5;        // short way, score is 20
Console.WriteLine(score);

Common assignment operators

OperatorExampleSame as
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3

Compound operators in action

int total = 100;
total -= 30; // 70
total *= 2;  // 140
total /= 7;  // 20
Console.WriteLine(total); // 20
Note: Compound assignment operators also work with strings when you use +=. For example, message += " world" adds text to the end of an existing string, which is handy for building up output piece by piece.
  • Use = to give a variable its first value.
  • Use +=, -=, *=, /=, or %= to update a variable based on what it already holds.
  • Compound operators make code shorter and easier to read, especially inside loops.