Making Decisions
8 min · C#
Run different code depending on whether something is true.
Enemy 1 of 5
if, else, and comparisons
An if statement runs its { } block only when the condition in parentheses evaluates to true. C#'s condition must actually be a bool (true or false) — unlike C, there's no automatic treating of numbers as true or false, which rules out a whole class of accidental bugs.
An else attached to an if provides the alternative path, running only when the if's condition was false. This gives you a clean two-way branch: do this, or otherwise do that.
Comparisons use > , < , >= , <= , == (equal to), and != (not equal to). A classic beginner slip in many C-family languages is confusing = (assignment) with == (comparison) — C# helps here, since if (x = 5) is actually a compile error in C# rather than a silent bug, because x = 5 produces an int, not a bool, and if requires a bool.
Loading editor...