05
Lesson 5 of 35 ยท Foundations

Operators & Expressions

Operators are the building blocks of expressions. In this lesson you will master arithmetic, comparison, logical, bitwise, and assignment operators, then learn operator precedence and the powerful pattern-matching operators introduced in recent C# versions.

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.

Arithmetic demo Arithmetic.cs
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.

Logical example Logic.cs
int age = 20;
bool hasId = true;

if (age >= 18 && hasId)
    Console.WriteLine("Access granted");

bool isEmpty = age == 0 || age < 0;
Console.WriteLine(!isEmpty); // true

Assignment 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.

Assignment operators Assignment.cs
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.

Ternary & null coalescing Ternary.cs
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