The if statement
Learn how to check a condition with if and the code block.
The if statement
To run code when a condition holds you use the if statement. You write a boolean expression in parentheses; when it is true the curly brace block runs, when false it is skipped.
For example, if (age >= 18) { Console.WriteLine("Can drive"); } prints the message when age is 18 or above. The condition always evaluates to true or false; nothing in between.
Conditions with logical operators
To combine several conditions you use && (and), || (or) and ! (not). if (age >= 18 && age <= 65) returns true when age is both 18 or above and 65 or below.
&& short-circuits: if the left side is false the right side is not evaluated. This makes safe checks like if (p != null && p.Length > 0) easy to write; if the left is false the right never runs.
Exercise Write the pass condition
Declare a score variable with the value 60. Use if to check score >= 50; when the condition holds, print "passed" with Console.WriteLine.
Show example solution
Write if (score >= 50) { Console.WriteLine("passed"); }
Example solution:
using System;
class Program
{
static void Main()
{
int score = 60;
if (score >= 50)
{
Console.WriteLine("passed");
}
}
}
Test yourself
-
With int age = 16; what does if (age >= 18) do?
int age = 16; if (age >= 18) Console.WriteLine("adult");- Prints nothing
- Prints 'adult'
- Raises a compile error
- Loops forever
Show answer
Prints nothing — Correct. 16 >= 18 is false, so the block is skipped.
-
Write the condition
int score = 75; if (____) { Console.WriteLine("passed"); }Show answer
int score = 75; if (score >= 50) { Console.WriteLine("passed"); } -
Match each operator to its meaning
- &&
- And (both true)
- ||
- Or (at least one true)
- !
- Not (flips the value)
- >=
- Greater than or equal