Skip to main content

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.

OperatorMeaningEquivalent
a++add 1a = a + 1
a--subtract 1a = 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.

OperatorEquivalent
a += xa = a + x
a -= xa = a - x
a *= xa = a * x
a /= xa = a / x

⚠️ With int, /= uses integer division: if a = 7, then a /= 2 makes a equal 3.

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:

FormIncrements a?Expression value
++ayesthe new value
a++yesthe 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)