Skip to content
dreamcode
dreamcode
Map
If & Else
Lesson 3 of 21
+15 XP on finish
C# FOUNDATIONSChapter 1 · C# Foundations

Branching with if and else

Use if statements to run code only when a condition is true. Combine them with else if to check other possibilities, and else for a default fallback.

Worked example
string sky = "rainy";
if (sky == "clear") {
    Console.WriteLine("Clear sky!");
} else if (sky == "rainy") {
    Console.WriteLine("Take an umbrella.");
} else {
    Console.WriteLine("Unknown sky.");
}

How it reads

  • if (sky == "clear") checks if the variable matches "clear"
  • else if checks another condition when the previous ones failed
  • else defines a block that runs if no conditions matched
Cloud tip: In C#, conditions inside if statements must evaluate to a boolean (bool). You cannot check raw integers or strings directly.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. What type must the condition of an if statement evaluate to in C#?
  2. 2. Which block runs if all preceding if/else-if conditions evaluate to false?
Answer every question to unlock the next lesson.