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.


