C#: Control Flow
What you will learn
Conditionals, loops, and the foreach loop that C# uses to iterate collections.
if / else if / else
int score = 85;
if (score >= 90) {
Console.WriteLine("A");
} else if (score >= 80) {
Console.WriteLine("B");
} else {
Console.WriteLine("F");
}
Loops
for loop
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
foreach loop (most common for collections)
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names) {
Console.WriteLine(name);
}
while loop
int i = 0;
while (i < 5) {
Console.WriteLine(i);
i++;
}
Switch statement
string day = "Monday";
switch (day) {
case "Monday":
Console.WriteLine("Start of work week");
break;
case "Friday":
Console.WriteLine("Almost weekend");
break;
default:
Console.WriteLine("Midweek");
break;
}
C# requires break at the end of each case (no fall-through unless you use goto case).
Common mistakes
- Forgetting
breakin aswitchcase — compile error in C# (prevents the classic C++ fall-through bug) - Writing
else ifas one word (elseif) — it's two words in C# - Modifying a collection inside a
foreachloop — use aforloop if you need to add/remove items
Quick check below!