Search code examples
c#roslyn-code-analysis

Can I force a non-exhaustive c# switch expression to cause a compile error?


I like switch expressions for mapping enums to values - while not the most scalable solution, it's fast and fairly clean if the enum represents something modal (and isn't huge).

One often source of bugs is adding members to an enum - which often leaves new cases unhandled.

But I think these bugs could be nearly wiped out if we could have compile errors for a non-exhaustive switch, making the omissions easily visible and fixable. (The default case has to be omitted though, otherwise it's all moot)

Is this possible? I'm thinking of something like this:

public string GetTargetValue()
{
    return target switch
   {
       Target.A => "foo",
       Target.B => "bar",
       // Compile error if someone added Target.C, otherwise works fine
       // no default case - it would defeat the point
   };
}

P.S: I work primarily in Unity, but to my understanding newer versions of Unity use the Roslyn compiler (I don't use burst) so I assume that doesn't matter.


Solution

  • Yes you can.

    This case raises the warning CS8509, as you can see here. To turn this into an error, add the following to your .editorconfig:

    dotnet_diagnostic.CS8509.severity = error
    

    You might also want to ignore CS8524, which happens if you don't have a default case, and CS8509 isn't being raised (so even if you're covering all possible values), see here. In this case, the compiler will insert a default case with throw new SwitchExpressionException(target):

    dotnet_diagnostic.CS8524.severity = none
    

    I suspect you probably need to be building with the .NET 5 SDK or higher for this warning to be generated.