Pattern matching errors and warnings

The compiler generates the following errors for invalid pattern match expressions:

  • CS9134: A switch expression arm does not begin with a 'case' keyword.
  • CS9135: A constant value of type is expected

The compiler generates the following warnings for incomplete pattern matching expressions:

  • CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '...' is not covered.

The compiler generates CS9134 to help you convert a switch statement to a switch expression. The case keyword isn't used in a switch expression. If you have the case keyword in a switch expression, it must be removed:

var answer = x switch
{
    // CS9134: remove the keyword "case" from each switch arm:
    case 0 => false,
    case 1 => true,
}

The compiler generates CS9135 when the pattern isn't a constant value. You can't create pattern matching expressions to match against a variable.

The following code snippets generate CS8509:

// CS8509.cs
enum EnumValues
{
    Value1,
    Value2,
    Value3
}

void Method(EnumValues enumValues)
{
    var result = enumValues switch
    {
        EnumValues.Value1 => 1,
        EnumValues.Value2 => 2,
    };
}

To address this warning, add switch arms that cover all possible input values. For example:

enum EnumValues
{
    Value1,
    Value2,
    Value3
}

void Method(EnumValues enumValues)
{
    var result = enumValues switch
    {
        EnumValues.Value1 => 1,
        EnumValues.Value2 => 2,
        EnumValues.Value3 => 3,
        _ => throw new ArgumentException("Input isn't a valid enum value", nameof(enumValues)),
        };
}

The _ pattern matches all remaining values. One scenario for the _ pattern is matching invalid values, as shown in the preceding example.

For more information, see Switch.