The flow of the program flows from top to bottom, branching with conditions and repeating with repeat. The switch expression, added after C# 8, provides clean pattern matching in the functional style.
Learning Objectives
- Conditional branch to
if/else if/else - Know the difference between the
switchstatement and theswitchexpression (=>) - Distinguish the use of
for/while/do-while/foreach - Control repetition with
breakandcontinue
Key concepts
1) if / else if / else
int score = 85;
if (score >= 90) Console.WriteLine("A");
else if (score >= 80) Console.WriteLine("B");
else if (score >= 70) Console.WriteLine("C");
else Console.WriteLine("F");
Conditions are evaluated in order from the top, so that only the branch that is true first is executed.
2) switch statement vs switch expression
statement type:
switch (day)
{
case 1: Console.WriteLine("month"); break;
case 2: Console.WriteLine("angry"); break;
default: Console.WriteLine("?"); break;
}
expression type — C# 8+:
string name = day switch
{
1 => "month",
2 => "angry",
_ => "?" //default role
};
Since the expression type returns a value, it can be directly assigned to a variable, and there is no need for break. _ is a wildcard that “matches any value”.
3) for / while / do-while
for: Repeat with a set number of timeswhile: Repeat while the condition is true (possible 0 times)do-while: Check conditions after executing once (at least once)
for (int i = 0; i < 3; i++) Console.WriteLine(i); // 0 1 2
int n = 3;
while (n > 0) { Console.WriteLine(n); n--; } // 3 2 1
int m = 0;
do { Console.WriteLine("once"); } while (m > 0); //just once
4) foreach
Iterates over IEnumerable, such as an array or list. Suitable for simple traversal that does not require an index.
int[] nums = [10, 20, 30];
foreach (int x in nums)
Console.WriteLine(x);
5) break / continue
break: Terminates the current loop immediatelycontinue: Skip current iteration to next iteration
for (int i = 1; i <= 10; i++)
{
if (i == 5) break; //Escape from i==5
if (i % 2 == 0) continue;//Skip even numbers
Console.WriteLine(i); //1, 3 output
}
See as example
Example 1 — IfElse/Program.cs: Determining grade level
Console.Write("Score:");
int score = int.Parse(Console.ReadLine()!);
string grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else grade = "F";
Console.WriteLine($"Grade: {grade}");
Execution result
Score: 85
Grade: B
Note: Since it is evaluated from top to bottom, you need to sort it from narrow condition or big value first to work as intended.
Example 2 — SwitchExpression/Program.cs: Day of the week
Console.Write("Day number (1~7):");
int day = int.Parse(Console.ReadLine()!);
string name = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
_ => "Invalid input"
};
Console.WriteLine(name);
Execution result
Day number (1~7): 3
Wednesday
Note: The switch expression will issue a warning if it does not cover all cases. Be sure to leave the default value as _.
Example 3 — ForWhile/Program.cs : for sum, while countdown
//sum from 1 to 10
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
Console.WriteLine($"1~10 sum = {sum}");
//Countdown from 5 to 1
int n = 5;
while (n > 0)
{
Console.Write($"{n} ");
n--;
}
Console.WriteLine("Fire!");
Execution result
1~10 sum = 55
5 4 3 2 1 Fire!
Note: Accumulated variables must be initialized outside the loop for the results to persist.
Example 4 — Foreach/Program.cs: Array sum
int[] scores = [78, 92, 64, 85, 100];
int total = 0;
foreach (int s in scores)
total += s;
double avg = (double)total / scores.Length;
Console.WriteLine($"Total score: {total}, average: {avg:F2}");
Execution result
Total score: 419, average: 83.80
Memo: Detailed usage of arrays is covered in Part 11. “Iterating over a bundle” is sufficient here.
Common Mistakes
- Confusing
<=and<likefor (int i = 0; i <= n; i++)— off-by-one bug. breakis missing from theswitchstatement — it is not in the expression type, but the statement type is required.- Infinite loop —
breakcondition is missing inwhile (true). - Modifying collection during
foreach— exception occurred. Useforto fix. - Incorrectly written as
if (a == 0 || 1)—if (a == 0 || a == 1)is correct.
Cleanup
- Branches:
if/elseandswitch(recommended expression type) - Repeat: Count —
for, Condition —while, At least 1 time —do-while, Collection —foreach - Escape to
break, skip tocontinue - The
switchexpression +_pattern is the recommended style in modern C#.
Try it yourself
cd src/IfElse && dotnet run
cd ../SwitchExpression && dotnet run
cd ../ForWhile && dotnet run
cd ../Foreach && dotnet run