Arithmetic Operators
The standard arithmetic operators are +, -, *, /, and % (modulus / remainder). Integer division truncates: 7 / 2 == 3. Cast at least one operand to double for decimal division.
int a = 17, b = 5; Console.WriteLine(a + b); // 22 Console.WriteLine(a - b); // 12 Console.WriteLine(a * b); // 85 Console.WriteLine(a / b); // 3 (integer division) Console.WriteLine(a % b); // 2 (remainder) Console.WriteLine((double)a / b); // 3.4
Comparison & Logical Operators
Comparison operators return bool: ==, !=, <, >, <=, >=. Logical operators combine booleans: && (AND), || (OR), ! (NOT). The short-circuit operators && and || skip the right operand if the result is already determined.
int age = 20;
bool hasId = true;
if (age >= 18 && hasId)
Console.WriteLine("Access granted");
bool isEmpty = age == 0 || age < 0;
Console.WriteLine(!isEmpty); // trueAssignment Operators
Compound assignment operators combine an operation with assignment: +=, -=, *=, /=, %=. The increment (++) and decrement (--) operators add or subtract 1. Prefix (++x) increments before use; postfix (x++) increments after use.
int x = 10; x += 5; // x = 15 x -= 3; // x = 12 x *= 2; // x = 24 x /= 4; // x = 6 x %= 4; // x = 2 int a = 5; Console.WriteLine(a++); // prints 5, then a becomes 6 Console.WriteLine(++a); // a becomes 7, prints 7
Ternary & Null-Coalescing
The ternary operator condition ? valueIfTrue : valueIfFalse is a compact if/else for expressions. The null-coalescing operator ?? returns the left value if non-null, otherwise the right. ??= assigns a value only if the variable is currently null.
int score = 75; string grade = score >= 60 ? "Pass" : "Fail"; Console.WriteLine(grade); // Pass string? name = null; name ??= "Anonymous"; // assigns only because name is null Console.WriteLine(name); // Anonymous