Control Flow

View saved

If and else

Braces are strongly recommended even for one-liners.

int age = 17;
if (age >= 18)
{
    Console.WriteLine("Adult");
}
else
{
    Console.WriteLine("Youth");
}

Switch expressions

Modern C# can return a value from a switch expression.

string day = "sat";
string kind = day switch
{
    "sat" or "sun" => "weekend",
    _ => "weekday"
};
Console.WriteLine(kind);

For and while

Use for when you know the bounds; while when you wait on a condition.

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine(i);
}

Flow tips

  • Use break and continue sparingly
  • Prefer clear boolean names for complex conditions
  • Watch inclusive vs exclusive bounds
  • Handle empty collections before indexing

Comments

One comment per signed-in account. Comments are saved with this page’s URL.