Lesson 3 of 40
Foundations
Beginner
โฑ 25 min
Control Flow โ if, switch, loops
Control how your program makes decisions and repeats work with if/else, switch expressions, for, foreach, while, and the new C# pattern-matching switch.
Part 1: if / else if / else
int score = 85;
if (score >= 90)
Console.WriteLine("Grade: A");
else if (score >= 80)
Console.WriteLine("Grade: B");
else
Console.WriteLine("Grade: C or below");
if (score >= 90)
Console.WriteLine("Grade: A");
else if (score >= 80)
Console.WriteLine("Grade: B");
else
Console.WriteLine("Grade: C or below");
Part 2: Switch Expressions (Modern C#)
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
The discard pattern {
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F"
};
_ acts as the default case. Switch expressions are exhaustive โ the compiler warns if you miss a case.Part 3: Loops โ for, foreach, while
// for loop
for (int i = 0; i < 5; i++)
Console.Write($"{i} ");
// foreach (preferred for collections)
var names = new[] {"Alice","Bob","Carol"};
foreach (var name in names)
Console.WriteLine(name);
// while loop
int n = 1;
while (n <= 5) { Console.Write(n++ + " "); }
for (int i = 0; i < 5; i++)
Console.Write($"{i} ");
// foreach (preferred for collections)
var names = new[] {"Alice","Bob","Carol"};
foreach (var name in names)
Console.WriteLine(name);
// while loop
int n = 1;
while (n <= 5) { Console.Write(n++ + " "); }
Part 4: break, continue & goto (avoid)
foreach (var item in items)
{
if (item.IsDeleted) continue; // Skip to next
if (item.IsError) break; // Exit loop entirely
Process(item);
}
// goto โ avoid in modern C#
// Use structured control flow instead
{
if (item.IsDeleted) continue; // Skip to next
if (item.IsError) break; // Exit loop entirely
Process(item);
}
// goto โ avoid in modern C#
// Use structured control flow instead
C# in Visual Studio 2026
๐ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition