Skip to content

Incorrect cast is redundant in switch expression with nullable value type. #36755

@dibarbet

Description

@dibarbet

Version Used:
Capture

Steps to Reproduce:

Input this code

class Program
{
    void M()
    {
        string numberString = "One";
        Numbers? number = numberString switch
        {
            "One" => (Numbers?)Numbers.One,
            "Two" => Numbers.Two,
            _ => null,
        };
    }
}

enum Numbers
{
    One,
    Two
}

The cast (Numbers?) in case "One" is marked as unnecessary.
Capture2

Removing the cast causes a compiler error.
Error CS0037 Cannot convert null to 'Numbers' because it is a non-nullable value type
Capture3

A few followup notes

  1. It is a little confusing that casting the first element of the switch expression is required, even if I explicitly define the expected return type as Numbers?. The IDE also offers no assistance that casting the first member of the switch expression may fix the compiler error.
  2. Converting a switch statement to switch expression in this instance yields invalid code (it doesn't add the appropriate cast to the first case).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions