C#C#

C#: Control flow – code examples

Contents

if / else if / else

Control flow#if#condition#elseCompare in all languages
Use case: React differently depending on the situation, e.g. calculate grades or price tiers.
int punkte = 73;
if (punkte >= 90)
    Console.WriteLine("excellent");
else if (punkte >= 70)
    Console.WriteLine("good");
else
    Console.WriteLine("needs improvement");

The condition must be a bool and goes in parentheses; blocks with { } are optional for single statements.

for and foreach loops

Control flow#for#foreach#loopCompare in all languages
Use case: Process every element of a list or repeat n times.
for (int i = 0; i < 3; i++)
{
    Console.WriteLine($"Runde {i}");
}

foreach (string frucht in new[] { "Apple", "Pear" })
{
    Console.WriteLine(frucht);
}

for counts with an index, foreach iterates directly over each element of a collection.

switch expression with patterns

Control flow#switch#pattern#relational
Use case: Write branches by type or value range compactly (price tiers, shapes, status codes).
Console.WriteLine(Groesse(5));    // small
Console.WriteLine(Groesse(50));   // medium
Console.WriteLine(Groesse(500));  // large

static string Groesse(int n) => n switch
{
    < 10 => "small",
    < 100 => "medium",
    _ => "large"
};

Relational patterns (< 10) in a switch expression replace long if chains. The arms are checked from top to bottom.