C#

Lesson 08

Pattern matching switches

Use pattern matching to make state-specific branches explicit and keep default cases from hiding unhandled states.

Good Code

src/ReviewStatusText.cs
public static string LabelFor(ReviewStatus status)
{
    return status switch
    {
        ReviewStatus.Draft => "Draft",
        ReviewStatus.Published => "Published",
        ReviewStatus.Archived => "Archived",
        // Unknown enum values fail loudly during review and tests.
        _ => throw new ArgumentOutOfRangeException(nameof(status), status, null)
    };
}

Bad Code

ReviewStatusText.cs
public static string LabelFor(ReviewStatus status)
{
    switch (status)
    {
        case ReviewStatus.Published:
            return "Published";
        default:
            // Default hides Draft, Archived, and future states.
            return "Draft";
    }
}

Review Notes

What to review

Good Code

The good version names every current status and throws for unknown values. New enum values become review-visible because tests or runtime fail fast.

Bad Code

The bad version sends every non-published status to Draft. Future statuses can ship with the wrong label and no compiler or test signal.

Takeaways

  • A C# switch expression should show each known state and make unknown states visible instead of silently falling through.