CodeBlanks Logo Icon CodeBlanks

Pattern matching

C# course · Beginner · Lesson 39/116

Learn modern C# conditions with switch expressions and type patterns.

Pattern matching

Modern C# lets you produce a value with a switch expression. var label = day switch { 1 => "monday", 2 => "tuesday", _ => "?" }; returns the result in one line.

The underscore _ means 'all other cases'; it is the expression equivalent of default. This form is especially readable when mapping one value to another and replaces the classic switch statement.

Type patterns and when

Switch expressions work not only with constants but also with type patterns. shape switch { Circle c => Math.PI * c.R * c.R, Square s => s.S * s.S, _ => 0 } picks the right branch by the object's type and binds a name to it.

For finer control you add a when guard: int n when n > 0 => "positive". This way both the type and an extra condition sit in one branch; even tricky cases stay clean.

Exercise Day name with a switch expression

Declare a day variable with the value 2. Use a switch expression to produce name: 1 => "monday", 2 => "tuesday", _ => "unknown". Then print name with Console.WriteLine.

Show example solution
Write string name = day switch { 1 => "monday", 2 => "tuesday", _ => "unknown" };
Example solution:
using System;

class Program
{
    static void Main()
    {
        int day = 2;
        string name = day switch { 1 => "monday", 2 => "tuesday", _ => "unknown" };
        Console.WriteLine(name);
    }
}

Test yourself

  1. In a switch expression, what marks 'all other cases'?

    var label = day switch { 1 => "one", _ => "?" };
    • default
    • else
    • *
    • _ (underscore)
    Show answer

    _ (underscore) — Correct. _ (discard pattern) catches all other cases.

  2. Match each switch expression part to its meaning

    switch
    Takes the value
    =>
    Produces the result
    _
    All other cases
    ;
    Ends the expression
  3. Write the result arrow

    string label = day switch { 1 ____ "monday", _ => "?" };
    Show answer
    string label = day switch { 1 => "monday", _ => "?" };

All lessons in Beginner