Select Page

A switch expression can cover every declared enum member and still leave some inputs unhandled. An enum also permits numeric values with no declared name. This tutorial builds a job-state label function, checks its rejection policy, and shows what the compiler can tell you when an arm is missing.

If you need the basic syntax first, read Lesson 17: enums and Lesson 3: selection statements. Here the goal is a small mapping with a deliberate policy for unexpected values.

Run a mapping with an explicit rejection policy

The examples were checked on 17 October 2026 with .NET SDK 10.0.402, target framework net10.0, and C# 14.0. Nullable analysis and warnings as errors were enabled. Use the .NET 10 SDK and an ordinary console project. The SDK selects the language version through the target framework; see Microsoft’s language-version configuration.

dotnet new console --framework net10.0 --name SwitchCoverage
cd SwitchCoverage

The checked examples used the following project settings. After creating your project, replace SwitchCoverage.csproj with these settings:

<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><TreatWarningsAsErrors>true</TreatWarningsAsErrors></PropertyGroup></Project>

Replace all of Program.cs with this complete program. The first loop checks the expected labels. The second calls the mapping for every declared state. The final loop requires rejection of zero and 99.

using System;

public enum JobState { Queued = 1, Running = 2, Finished = 3 }

public static class Program
{
    public static string Label(JobState state) => state switch
    {
        JobState.Queued => "waiting",
        JobState.Running => "working",
        JobState.Finished => "done",
        _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown job state")
    };

    public static void Main()
    {
        (JobState State, string Expected)[] cases =
        {
            (JobState.Queued, "waiting"),
            (JobState.Running, "working"),
            (JobState.Finished, "done")
        };
        foreach (var item in cases)
        {
            string actual = Label(item.State);
            if (actual != item.Expected)
                throw new InvalidOperationException("Incorrect label");
            Console.WriteLine($"{item.State}: {actual}");
        }

        foreach (JobState state in Enum.GetValues<JobState>())
        {
            _ = Label(state);
        }
        Console.WriteLine("All named states have labels.");

        foreach (int raw in new[] { 0, 99 })
        {
            try
            {
                _ = Label((JobState)raw);
                throw new InvalidOperationException("Unknown state was accepted");
            }
            catch (ArgumentOutOfRangeException error) when (error.ParamName == "state")
            {
                Console.WriteLine($"Rejected: {raw}");
            }
        }
    }
}

Run dotnet run. The exact application output is:

Queued: waiting
Running: working
Finished: done
All named states have labels.
Rejected: 0
Rejected: 99

The mapping’s input appears before switch. Each comma-separated arm has a pattern, =>, and a result expression. The named states return labels. The final discard pattern, _, sends every remaining value to an explicit exception. Microsoft’s switch-expression reference documents arm selection and discard patterns.

The enum deliberately starts at 1 to expose the default-value edge case. Microsoft generally recommends defining a zero-valued member; choose its meaning deliberately in production code. Its default value is still zero, which has no name here. Casting 99 to this enum is also permitted. Neither value is one of this application’s supported states, so the function rejects both. See the enum reference for default values and numeric conversions.

Compare two missing-case diagnostics

Replace Program.cs with the next program. It includes every named member but omits the catch-all arm. Keep the project settings above and build it with dotnet build; this example is intentionally expected to fail. The TreatWarningsAsErrors property makes the missing-case warnings fail the build.

using System;

public enum JobState { Queued = 1, Running = 2, Finished = 3 }

public static class Program
{
    public static string Label(JobState state) => state switch
    {
        JobState.Queued => "waiting",
        JobState.Running => "working",
        JobState.Finished => "done"
    };

    public static void Main() => Console.WriteLine(Label(JobState.Queued));
}

On the tested compiler this produces CS8524: unnamed enum values remain uncovered. Without warnings as errors, this diagnostic is a warning. A complete list of names does not cover every numeric value the enum can hold.

Now use this complete version, which also omits the named Finished case:

using System;

public enum JobState { Queued = 1, Running = 2, Finished = 3 }

public static class Program
{
    public static string Label(JobState state) => state switch
    {
        JobState.Queued => "waiting",
        JobState.Running => "working"
    };

    public static void Main() => Console.WriteLine(Label(JobState.Queued));
}

With these project settings, the checked build produces CS8509. The distinction is useful during review: one example misses unnamed values; the other misses a declared state. These diagnostic IDs were checked by compiling both programs, with no executable output expected.

For an unmatched value, a nonexhaustive switch expression throws SwitchExpressionException on .NET 10. That is different from our first program’s deliberately chosen ArgumentOutOfRangeException. The nonexhaustive-switch documentation describes this runtime behavior.

Keep the catch-all last

This complete program is another intentional build failure:

using System;

public static class Program
{
    public static string Label(int value) => value switch
    {
        _ => "any value",
        0 => "zero"
    };

    public static void Main() => Console.WriteLine(Label(0));
}

The compiler reports CS8510 because the first arm already covers zero. Put specific cases before the catch-all. When guards are present, the first matching arm whose guard succeeds supplies the result; the case-guard reference explains that ordering.

Check coverage again when the enum grows

Restore the first, working program. Add a fourth enum member, Paused = 4, while leaving Label unchanged. The discard arm means the switch still compiles. Running the original coverage loop now throws when it reaches Paused. The build alone cannot tell you that your application needs a new label.

Keep that loop uncaught in a regression test so the new member fails the test until you add its intended mapping. Enum.GetValues<TEnum> supplies the declared values; it does not enumerate all possible numeric casts.

The checks have different jobs: expected-label assertions protect the meaning of current states, the declared-value loop catches newly added states that reach the rejection arm, and the zero/99 checks protect the rejection policy for those two inputs. Passing them does not prove every possible future state has the correct meaning.

For a small enum mapping, give each supported state an explicit arm, decide what unknown values should do, and test both the named cases and representative unexpected inputs. For ordered business rules with property patterns and guards, continue to pattern matching for first-error validation.

Verification used a fixed console project with the settings shown above; the setup commands are documented reader instructions. Fixture results: two successful program runs, three expected diagnostic failures, and one compiler/language-version probe. Project creation and running commands follow Microsoft’s console-template and dotnet run references.

Share This