Programs that decide
People make decisions from conditions all day: if it is raining, bring an umbrella; if you are hungry, eat. An if statement lets a C# program do the same. It runs a block of code only when a condition holds.
bool isRainy = true;
if (isRainy) {
Console.WriteLine("I bring an umbrella");
}
This prints I bring an umbrella. With isRainy set to false it prints nothing, and the program moves on to whatever comes after the closing brace.
The syntax
if (condition) {
// runs only when the condition is true
}
The condition goes inside parentheses, and the code to run goes inside curly braces. Everything between the braces is the block. If the condition is false, C# skips the whole block.
Boolean conditions
The condition must be a bool: a value that is either true or false. It can be a bool variable, as above, or the result of a comparison:
int age = 20;
if (age >= 18) {
Console.WriteLine("Adult");
}
The comparison operators are == (equal), != (not equal), <, >, <= and >=. Each produces a bool.
When a variable is already a bool, use it directly. Writing if (isRainy == true) works but only repeats what if (isRainy) says.
Adding else
An else block runs when the condition is false, so the program responds either way:
bool amHungry = false;
if (amHungry) {
Console.WriteLine("I have breakfast");
} else {
Console.WriteLine("I skip breakfast");
}
Here amHungry is false, so the program prints I skip breakfast. Exactly one of the two blocks runs. An else has no condition of its own: it covers every case that the if did not.
More than two outcomes
When there are more than two cases, chain them with else if. C# tests the conditions from top to bottom and runs the first block whose condition is true:
int score = 75;
if (score >= 90) {
Console.WriteLine("A");
} else if (score >= 70) {
Console.WriteLine("B");
} else {
Console.WriteLine("C");
}
This prints B. The first condition is false, the second is true, and the final else is skipped. Once one block has run, the rest of the chain is ignored.
The exercise, step by step
The lesson starts with bool passed = true; and builds a small program on it.
- Write the
if. The condition is justpassed, in parentheses, followed by{to open the block. - Print the success message. Inside the block,
Console.WriteLine("Passed the test");runs only whenpassedis true.WriteLineends the line, so each message gets its own line. - Add the
else. Write} else {on one line, which closes theifblock and opens theelseblock. Print"Failed"inside and close with}.
bool passed = true;
if (passed) {
Console.WriteLine("Passed the test");
} else {
Console.WriteLine("Failed");
}
Since passed is true, the program prints Passed the test. If you change the first line to bool passed = false; it prints Failed, which is a good way to check both branches.
C# details to know
- Only a
boolworks as a condition. C# does not treat numbers or strings as true or false.if (1)andif (name)are compile errors, unlike in some other languages. - One equals sign assigns, two compare.
if (x = 5)is an error for anint, andif (x == 5)is the check you want. With aboolvariableflag, the slipif (flag = true)does compile. It setsflagto true and always runs the block, and the compiler warns about it. - Keep the braces. C# lets you leave them off for a single statement, but only that one statement belongs to the
if. A second indented line would run every time. Always writing braces avoids that trap. - No semicolon after the condition.
if (passed);ends the statement immediately, so the block after it is not controlled by the condition.
Common mistakes
- Forgetting the parentheses around the condition. C# requires them.
- Writing
ElseorIfwith a capital letter. Keywords are lowercase. - Putting a condition on
else.else (x > 3)is invalid. To test another condition, useelse if. - Using
console.writeline. The name isConsole.WriteLine, with capitals.
Key takeaways
if (condition) { ... }runs the block only when the condition is true.- The condition must be a
bool, such as a variable or a comparison. elsecovers the case where the condition is false.- Use
==to compare and=to assign. - Always use curly braces, even for one statement.