Control Flow
Definition
Control flow refers to the order in which individual statements, instructions, or function calls are executed in a program. C# provides conditional statements (if, switch) for branching, loops (for, foreach, while, do-while) for iteration, and jump statements (break, continue, return) for transferring control.
Core Concepts
if / else if / else
The if statement evaluates a Boolean expression and executes a block conditionally.
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
// Output: Grade: B
When the body is a single statement, braces are technically optional but always use braces for readability and to prevent bugs when adding lines later.
switch Statement
The switch statement selects a section to execute from a list of candidates based on a pattern match.
Traditional switch:
string dayOfWeek = DateTime.Now.DayOfWeek.ToString();
switch (dayOfWeek)
{
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
Console.WriteLine("Weekday");
break; // C# requires explicit break
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Unknown");
break;
}
Switch with pattern matching (C# 7+):
object value = 42;
switch (value)
{
case int i when i > 0:
Console.WriteLine($"Positive integer: {i}");
break;
case string s:
Console.WriteLine($"String of length {s.Length}");
break;
case null:
Console.WriteLine("Null value");
break;
default:
Console.WriteLine("Something else");
break;
}
Switch Expressions (C# 8+)
Switch expressions are more concise and return a value. They use pattern matching with the => arrow syntax.
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
>= 60 => "D",
_ => "F" // _ is the discard pattern (default)
};
With tuple patterns:
string Classify(int x, int y) => (x, y) switch
{
(0, 0) => "Origin",
(> 0, > 0) => "Quadrant I",
(< 0, > 0) => "Quadrant II",
(< 0, < 0) => "Quadrant III",
(> 0, < 0) => "Quadrant IV",
(0, _) or (_, 0) => "On an axis"
};
Switch expressions are more concise, expression-oriented, and less error-prone than switch statements. Use them when you need to produce a value from a multi-way branch.