Skip to content
Learn Netverks

Lesson

Step 25/36 69% through track

pattern-matching-csharp

Pattern matching

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Pattern matching: the syntax, patterns, and safety habits you need before advancing in C#.

Teams still ship Pattern matching in C# codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Pattern matching in contexts like: .NET services, Unity games, and Windows-centric tooling.

Write C# with Console.WriteLine (top-level or Program), click Run on server—the dev runner uses dotnet build/run on a temp net8 project (requires .NET SDK; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Modern C# pattern matching unifies type tests, property deconstruction, and switch expressions—more expressive than chained if/else or instanceof checks in Java.

is patterns and switch

if (obj is string { Length: > 0 } s) {
    Console.WriteLine(s);
}

string label = shape switch {
    Circle c => $"circle r={c.Radius}",
    Rectangle r => $"rect {r.Width}x{r.Height}",
    _ => "unknown"
};

Relational and logical patterns

int score = 85;
string grade = score switch {
    >= 90 => "A",
    >= 80 => "B",
    _ => "C"
};

Important interview questions and answers

  1. Q: Switch expression vs statement?
    A: Expressions return values and use => arms; statements use case/break for side effects.
  2. Q: Exhaustiveness?
    A: Compiler warns when switch on enums/types misses cases—use _ discard for defaults.

Self-check

  1. What does the _ arm represent?
  2. How do property patterns help with null checks?

Tip: Combine is patterns with switch expressions—cleaner than long if/else chains for type and shape checks.

Interview prep

is pattern vs cast?

is patterns test and bind in one step—safer than manual cast followed by null check.

switch expression exhaustiveness?

Compiler warns when not all cases are covered—especially useful with enums and records.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • switch type pattern?
  • is not null?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump