C#C# · Lesson 3 of 9

Control Flow

C# control flow is classic C-family. The highlight is pattern matching in switch statements, which is genuinely one of C#'s best features.

C#
int score = 85;

// if/else if/else
if (score >= 90) Console.WriteLine("A");
else if (score >= 80) Console.WriteLine("B");
else if (score >= 70) Console.WriteLine("C");
else Console.WriteLine("Try harder");

// Ternary
string grade = score >= 60 ? "Pass" : "Fail";

// switch with pattern matching (C# 7+)
object shape = "circle";

string desc = shape switch {
    "circle"    => "Round thing",
    "square"    => "Four equal sides",
    int n when n > 0 => $"Positive number: {n}",
    null        => "Nothing",
    _           => "Unknown"   // default
};
Console.WriteLine(desc);

// Classic switch
int day = 2;
switch (day) {
    case 1:
        Console.WriteLine("Monday"); break;
    case 6:
    case 7:
        Console.WriteLine("Weekend"); break;
    default:
        Console.WriteLine("Weekday"); break;
}
C#
// for loop
for (int i = 0; i < 5; i++) {
    Console.Write($"{i} ");
}
Console.WriteLine();

// foreach — iterate over collections
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits) {
    Console.WriteLine(fruit);
}

// while
int n = 10;
while (n > 0) {
    Console.Write($"{n} ");
    n -= 3;
}

// LINQ — Language Integrated Query (C#'s killer feature)
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evens = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);
var evenSquares = numbers.Where(n => n % 2 == 0).Select(n => n * n);
int sum = numbers.Sum();
int max = numbers.Max();

foreach (int n2 in evenSquares) {
    Console.Write($"{n2} ");   // 4 16 36 64 100
}
◆ Note
LINQ (Language Integrated Query) is one of C#'s most powerful features. It lets you query collections (and databases, and XML) using a uniform syntax. Learn it — you'll use it constantly.