You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Control flow statements determine the order in which code executes. C# provides traditional branching and looping constructs along with modern pattern matching features.
The most basic branching statement:
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");
}
string result = score >= 60 ? "Pass" : "Fail";
Traditional switch with constant patterns:
string dayType = day switch
{
DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",
_ => "Weekday"
};
switch (command)
{
case "start":
Start();
break;
case "stop":
Stop();
break;
case "restart":
Stop();
Start();
break;
default:
Console.WriteLine("Unknown command");
break;
}
A more concise syntax that returns a value:
string description = statusCode switch
{
200 => "OK",
301 => "Moved Permanently",
404 => "Not Found",
500 => "Internal Server Error",
_ => $"Unknown status: {statusCode}"
};
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.