Unary & Binary Operators
C# has shorthand operators for updating a variable based on its current value.
Increment and Decrement (Unary)
Unary operators act on a single operand.
| Operator | Meaning | Equivalent |
|---|---|---|
a++ | add 1 | a = a + 1 |
a-- | subtract 1 | a = a - 1 |
Unary Operator Example
int apples = 5;
apples++; // translation: apples = apples + 1; so apples = 6
Compound Assignment (Binary)
Binary operators combine an arithmetic operation with assignment. They take two operands, so they are not unary.
| Operator | Equivalent |
|---|---|
a += x | a = a + x |
a -= x | a = a - x |
a *= x | a = a * x |
a /= x | a = a / x |
⚠️ With
int,/=uses integer division: ifa = 7, thena /= 2makesaequal3.
Binary Operator Example
int a = 1;
int b = 2;
a += b; // translation: a = a + b; so a = 3
Prefix vs Postfix
++ and -- can go before (prefix) or after (postfix) the variable.
On a line by itself, there's no difference:
int apples = 5;
apples++; // apples is 6
++apples; // apples is 7
The difference appears when the result is used in an expression:
| Form | Increments a? | Expression value |
|---|---|---|
++a | yes | the new value |
a++ | yes | the old value |
Prefix example
int a = 5;
int b = 4;
b = ++a + b; // a becomes 6, then 6 + 4
Console.WriteLine($"a = {a}, b = {b}"); // a = 6, b = 10
Postfix example
int a = 5;
int b = 4;
b = a++ + b; // uses 5, then a becomes 6 → 5 + 4
Console.WriteLine($"a = {a}, b = {b}"); // a = 6, b = 9
In both cases a ends up as 6. Only the value used in the calculation differs.
💡 Best practice: Increment/Decrement on its own line instead (for readability)