Is this a C# switch expression exhaustiveness check bug?

117 Views Asked by At
public enum Test { Yes, No }

I have these two switch expressions. The one below gives a CS8509 warning:

Test? test = null;
var result = test switch
{
    null => "Null",
    Test.Yes => "Yes",
    Test.No => "No",
};

But moving the null case to the end resolves it. Does anybody know why this happens? This has to be a bug, correct?

Test? test = null;
var result = test switch
{
    Test.Yes => "Yes",
    Test.No => "No",
    null => "Null",
};

Project settings:

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <LangVersion>10.0</LangVersion>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <NoWarn>8524</NoWarn>
</PropertyGroup>
1

There are 1 best solutions below

3
Guru Stron On BEST ANSWER

Found this issue at the github with very similar problem. The resolution is:

From discussion with team members, this is by design. The compiler's commitment is to provide a diagnostic, but exactly which diagnostic is a question that's reserved and we keep flexibility on that.

You have disabled one of the (at least) two warnings possible here, so you get this inconsistent behaviour. The same can be reproduced the other way around:

#pragma warning disable CS8509

// no warning 
static void F(Test? test) {
    var result = test switch
 {
     null => "Null",
     Test.Yes => "Yes",
     Test.No => "No",
 };
}

// warning 
static void F(Test? test) {
    var result = test switch
 {
     Test.Yes => "Yes",
     Test.No => "No",
     null => "Null",
 };
}

Demo @sharplab