Split CS8509 into unhandled named and unnamed enum values
See original GitHub issueBrief description:
CS8509 is a warning you get when a switch expression doesn’t have a pattern for certain enum values. You get the same warning when the enum value is named as when the value is unnamed (via a cast like (EnumType)9
).
This means that even when every named enum value has been handled you still get a warning. This encourages programmers to add a pattern that handles every case (often times this case simply throws an exception i.e. _ => throw new ..
).
But that means that when you add a new named value to your enum you won’t get a warning since it has already been handled (incorrectly) by the catch-all pattern.
My suggestion:
If instead you get a different warning depending on whether or not the unhandled enum value is named or unnamed, people could decide for themselves how they would like to approach this issue by enabling/disabling the appropriate warning.
Languages applicable:
C#, I’m not sure if VB has switch expressions.
Code example that the analyzer should report:
With this enum:
public enum Operation
{
Plus,
Minus,
Multiply,
}
this code:
public static string OperationToString(Operation op)
{
return op switch
{
Operation.Plus => "+",
Operation.Minus => "-",
// Note!: Operation.Multiply has not been handled by accident
};
}
and this code:
public static string OperationToString(Operation op)
{
return op switch
{
Operation.Plus => "+",
Operation.Minus => "-",
Operation.Multiply => "*",
// Note!: Every named enum value has been handled
};
}
should be reported with different warnings.
Additional information:
I expect neither warning to trigger when you add a catch-all pattern. This means that when you intend for your switch expression to handle every named value you would generally not add a catch-all pattern so that you get an alert on those switch expressions when you add a new named enum value.
I think the [Flags] attribute should cause unnamed enum values that can be created by using bitwise or
on named enum values should also be considered named for the purposes of these warning.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:10
- Comments:7 (1 by maintainers)
I think the current implementation of this doesn’t work well.
If you supress CS8524 in .editorconfig (the warning that promts you to add the discard pattern) you end up supressing it for all switches, including the ones that doesn’t have enums. Having this rule avaliable for those cases (not enums) is as important as CS8509 for enums switches. A better approach would be to separate CS8524 in two different warnings: one for enums and other for not enums, or simply don’t apply ever CS8524 to enums and leave only CS8509 for them.
Right now I need to supress CS8524 in every switch with enums so I can get the best of both worlds. It works, but it’s not ideal.
Very nice to have found this issue. I’ve added the following rules to my
.editorconfig
:and love the result.