Skip to main content

Lesson 3 of 9

Pattern Matching - Switch Expressions & Guards

Pattern matching in C# 8-12 provides expressive, compiler-verified branching that eliminates verbose if/else chains. Essential for domain logic, discriminated unions, and mapping command results to HTTP responses in ASP.NET Core endpoints.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Switch Expressions & Property Patterns

Switch Expressions & Property Patterns
// ━━ Switch expression - maps input to output, exhaustive ━━
public static IResult MapResultToHttpResponse<T>(Result<T> result) =>
    result switch
    {
        { IsSuccess: true, Value: var value } => Results.Ok(value),
        { Error: NotFoundError notFound }     => Results.NotFound(notFound.Message),
        { Error: ValidationError validation } => Results.UnprocessableEntity(validation.Errors),
        { Error: ConflictError conflict }     => Results.Conflict(conflict.Message),
        _                                     => Results.InternalServerError()
    };

// ━━ Type patterns - safe casting + branching ━━
public static string DescribePayment(object payment) =>
    payment switch
    {
        CreditCardPayment { CardType: "Visa" } card   => $"Visa ending in {card.Last4}",
        CreditCardPayment { CardType: "MC" } card      => $"MasterCard ending in {card.Last4}",
        BankTransferPayment { BankName: var bank }     => $"Bank transfer via {bank}",
        CryptoPayment { Currency: "BTC" }              => "Bitcoin payment",
        null                                            => throw new ArgumentNullException(nameof(payment)),
        _                                               => "Unknown payment method"
    };

// ━━ List patterns (C# 11) ━━
public static string DescribeRoute(string[] segments) =>
    segments switch
    {
        []                              => "Root",
        ["api"]                         => "API root",
        ["api", "v1", var resource]     => $"V1 resource: {resource}",
        ["api", var version, var res, var id] => $"{version}/{res}/{id}",
        [.., "health"]                  => "Health endpoint",
        _                               => "Unknown route"
    };

// Placeholder types for compilation
record Result<T>(bool IsSuccess, T? Value = default, Exception? Error = null);
record NotFoundError(string Message) : Exception(Message);
record ValidationError(string[] Errors) : Exception(string.Join(", ", Errors));
record ConflictError(string Message) : Exception(Message);
record CreditCardPayment(string CardType, string Last4);
record BankTransferPayment(string BankName);
record CryptoPayment(string Currency);

Tip

Tip

Practice Pattern Matching Switch Expressions Guards in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Pattern Matching Switch Expressions Guards from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Pattern Matching Switch Expressions Guards is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/9 done