← Вернуться к курсу: C# from scratch

switch, switch expressions and pattern matching

Видео скоро появится

When a variable can have many possible values and each one leads to a different action, a long chain of else if becomes heavy. That is what switch is for. C# has improved it over the years, and today you have two forms: the classic switch statement and the shorter, more modern switch expression. Both rely on pattern matching, which lets you compare not just with exact values but with ranges, types and combinations.

The switch statement

Each case has a value and ends with break; if you forget it, the compiler gives an error, because C# does not allow "falling through" to the next case like other languages. Several cases in a row can share the same statements. The default block handles everything that matches no case, and it is always good to include it. Switch works with int, char, string, enum and other types; with strings it is case sensitive, so normalize the input with ToLower before comparing.

csharp
int day = 6;

switch (day)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        Console.WriteLine("Weekday");
        break;
    case 6:
    case 7:
        Console.WriteLine("Weekend");     // this one runs
        break;
    default:
        Console.WriteLine("Invalid day");
        break;
}

The switch expression

The switch expression returns a value, so it is ideal to turn an input into a result. It is written value switch { pattern => result, ... }, with a comma between branches, and the underscore _ as the final branch that catches everything else. The compiler checks that you cover all possible cases; if one is missing, it warns you. It is shorter than the classic switch and needs no break, because each branch is an expression, not a sequence of statements.

csharp
string command = "stop";

string description = command switch
{
    "start" => "Starting the engine",
    "stop"  => "Stopping the engine",
    "pause" => "Pausing",
    _       => "Unknown command"
};
Console.WriteLine(description);   // Stopping the engine

int hour = 14;
string greeting = hour switch
{
    < 12 => "Good morning",
    < 18 => "Good afternoon",
    _    => "Good evening"
};
Console.WriteLine(greeting);      // Good afternoon

Patterns: ranges, and, or, not and when

Relational patterns (<, <=, >, >=) and the combinators and, or and not let you express ranges in a very readable way, such as >= 12 and < 18. You can also check the type of a value with is and declare a variable in the same step, and add an extra condition with when. Keep the order in mind: branches are evaluated from top to bottom, and the compiler warns you if a branch could never be reached because an earlier one already covers it.

csharp
int age = 15;
string group = age switch
{
    < 0            => "Invalid",
    < 12           => "Child",
    >= 12 and < 18 => "Teen",
    >= 65          => "Senior",
    _              => "Adult"
};
Console.WriteLine(group);                 // Teen

object value = 42;
if (value is int n and > 10)
{
    Console.WriteLine($"Big int: {n}");   // Big int: 42
}

string result = value switch
{
    int i when i % 2 == 0 => "Even number",
    int                   => "Odd number",
    string s              => $"Text of {s.Length} chars",
    null                  => "Nothing",
    _                     => "Something else"
};
Console.WriteLine(result);                // Even number

char letter = 'e';
bool isVowel = letter is 'a' or 'e' or 'i' or 'o' or 'u';
Console.WriteLine(isVowel);               // True

Проверьте себя

Вопрос 1 из 2

What happens if you forget break in a case with statements?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →