Level 1 / C# Fundamentals / fundamental 3 of 7
Making decisions with if and else
Programs earn their keep by reacting: low fuel, high wind, a wrong password. if takes the bool expressions you drilled last time and decides which code runs. In these reps, always write the braces, even around a single line; it is the habit that keeps later edits from breaking.
Understand the idea
A condition in parentheses
if (condition) runs the block in braces only when the condition is true. The condition must be a bool, so if (count) is an error in C#; write if (count > 0) instead.
else if chains are checked top down
C# tests each condition in order and runs only the first one that is true, then skips the rest. That is why the strictest check (score >= 90) goes before the looser one (score >= 80).
The ternary operator
condition ? valueIfTrue : valueIfFalse is an expression, not a statement. Use it to pick between two values when assigning; use if when you need to run statements.
English to C#
“If age is 18 or more, print "Adult".”
if (age >= 18){Console.WriteLine("Adult");}
- if
- only run the block when...
- (age >= 18)
- ...this bool expression is true
- { ... }
- the block that runs
Rep 1 of 12
Copy itIn English
If age is 18 or more, print "Adult".
Type the code shown below. Watch it turn green as you go.
if (age >= 18){Console.WriteLine("Adult");}
Waiting for you to type · 0 of 15 pieces
Ctrl+Enter checks or moves on. Tab indents. Paste is off on purpose: your hands are learning this too.
Reps
0 of 12 done
Reps unlock in order, because each one builds on the last.
How your code is checked
Drills compare what you type with known-correct C#, token by token. Spacing, line breaks, and comments do not matter; spelling, case, and punctuation do. It is not a compiler, so it accepts the listed spellings of each answer and nothing else.
Try it in a real .NET project
Ask for a temperature with Console.ReadLine, parse it, and print a different message for freezing, mild, and hot. Then swap the order of your else if checks so the loosest one comes first and watch which messages stop appearing.
Check your understanding
With if (score >= 80) written before else if (score >= 90), what does a score of 95 print, and why?
Show the explanation
It prints the 80 branch. The chain stops at the first true condition, and 95 >= 80 is true, so the 90 check never runs. Put the strictest condition first so each branch can actually be reached.
Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.