LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1118 min read

Operators

Learn arithmetic, comparison, logical, assignment, and null-coalescing operators in C#.

Arithmetic Operators

OperatorMeaningExample
+Addition5 + 2 → 7
-Subtraction5 - 2 → 3
*Multiplication5 * 2 → 10
/Division5 / 2 → 2 (int) or 2.5 (double)
%Modulus (remainder)5 % 2 → 1
Integer Division Truncates

When both operands are integers, `/` discards the remainder instead of rounding. `5 / 2` gives `2`, not `2.5` — cast at least one operand to `double` first if you need a fractional result: (double)5 / 2 gives 2.5.

The modulus operator (%) is genuinely useful beyond simple remainders — it's the standard way to check for even/odd numbers, wrap a value around a fixed range, or determine "every Nth item" in a loop.

int number = 17;
bool isEven = number % 2 == 0; // false — 17 is odd
int hour = 25;
int wrapped = hour % 24; // 1 — wraps around a 24-hour clock

Increment & Decrement

++ and -- add or subtract 1 from a variable. Both come in a prefix form (++x, changes the value before it's used in the surrounding expression) and a postfix form (x++, changes the value after it's used) — a subtle but real difference.

int x = 5;
Console.WriteLine(x++); // 5 — prints the OLD value, then increments
Console.WriteLine(x); // 6
int y = 5;
Console.WriteLine(++y); // 6 — increments FIRST, then prints the new value

Compound Assignment Operators

These combine an arithmetic operation with assignment in one concise step, and are used constantly in real code.

OperatorEquivalent To
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = x / 2

Comparison Operators

int a = 5, b = 10;
Console.WriteLine(a == b); // False
Console.WriteLine(a != b); // True
Console.WriteLine(a < b); // True
Console.WriteLine(a <= 5); // True
Console.WriteLine(b >= 11); // False
== on Reference Types Compares References, Not Content (Usually)

For custom classes, == checks whether two variables point to the exact same object in memory by default, not whether their contents are equal — string is a special, deliberate exception where == does compare content. This distinction is covered in full once classes are introduced later in this course.

Logical Operators & Short-Circuiting

OperatorMeaning
&&Logical AND — both conditions must be true
||Logical OR — at least one condition must be true
!Logical NOT — inverts a boolean

&& and || "short-circuit" — meaning C# stops evaluating as soon as the overall result is already determined, skipping the remaining condition(s) entirely. This isn't just an optimization; it's a behavior you can deliberately rely on.

string? name = null;
// Without short-circuiting, this would throw if name were null.
// && stops immediately after "name != null" evaluates to false,
// so name.Length is never actually evaluated:
if (name != null && name.Length > 0)
{
Console.WriteLine("Has a name");
}
Fun Fact

C# also has non-short-circuiting logical operators, & and |, which always evaluate both sides regardless — genuinely rare to see in everyday code, but they exist for cases (mostly bitwise operations, a more advanced topic) where evaluating both sides deliberately matters.

The Ternary Operator

The ternary conditional operator (?:) is a compact, single-expression alternative to a simple if/else — useful when you're choosing between two values to assign, not running two different blocks of statements.

int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(status); // Adult

Null-Coalescing Operators

These are distinctly modern C# features for working safely and concisely with nullable values, avoiding verbose if (x == null) checks scattered throughout your code.

string? name = null;
string displayName = name ?? "Guest"; // ?? provides a fallback if name is null
Console.WriteLine(displayName);
name ??= "Anonymous"; // ??= assigns only if name is currently null
Console.WriteLine(name);
Output

Click Run to see what this code prints.

A closely related operator, the null-conditional ?., safely accesses a member only if the object isn't null, short-circuiting to null instead of throwing.

string? name = null;
int? length = name?.Length; // null, instead of throwing a NullReferenceException
Console.WriteLine(length ?? -1); // -1 — combining ?. and ?? is a very common pattern

Operator Precedence

Just like standard math, C# evaluates some operators before others when they appear in the same expression without parentheses.

PriorityOperators
Highest() — parentheses, evaluated first
++ -- ! (unary)
* / %
+ -
< > <= >=
== !=
&&
Lowest||
When in Doubt, Use Parentheses

Even when you're confident about precedence rules, adding explicit parentheses — like (a && b) || c instead of a && b || c — makes your intent unmistakable to any future reader, including yourself in six months.

Common Beginner Mistakes

Confusing = with ==

if (isReady = true) assigns true to isReady (and the condition is always true) rather than comparing it — a classic, easy-to-miss bug across every C-family language.

Expecting 5 / 2 to give 2.5

Integer division truncates the result — cast at least one operand to double first if you need a fractional answer.

Confusing x++ and ++x in a larger expression

int y = x++ + 1; and int y = ++x + 1; can produce different results — when in doubt, put the increment on its own line to avoid ambiguity entirely.

Relying on & or | when && or || (short-circuiting) was intended

Using the non-short-circuiting versions can trigger a null-reference exception in exactly the scenario short-circuiting was meant to protect against.

FAQs

`=` assigns a value; `==` compares two values for equality. Mixing them up is one of the most common beginner errors in C-family languages, though C# helpfully refuses to compile if (x = true) when x isn't a bool, catching many accidental cases.

Similar in spirit, but ?: is an expression that produces a value directly (usable in an assignment), while if/else is a statement that runs one of two code blocks — they overlap for simple value-choosing cases but aren't fully interchangeable.

Yes — a?.b?.c safely stops and returns null at the very first null link in the chain, rather than needing a separate null check for every step.

If the second condition in an && or || involves an expensive operation (like a database call), short-circuiting avoids running it unnecessarily whenever the first condition already determines the result.

Key Takeaways

  • Arithmetic operators perform math; integer division truncates rather than rounding.
  • Comparison operators return a bool; logical operators (&&, ||) short-circuit for both safety and efficiency.
  • The ternary operator (?:) is a compact expression form of if/else for choosing between two values.
  • ?? and ??= provide clean, safe fallback handling of null values; ?. safely accesses a member only if the object isn't null.
  • When precedence isn't immediately obvious, explicit parentheses make intent clear to any future reader.

Summary

C#'s operators — arithmetic, comparison, logical, and the distinctly modern null-handling operators — form the vocabulary every later control-flow lesson builds on. Next, you'll learn how to actually read input from and write output to the console.

Next Lesson →

Input & Output