Exhaustive pattern matching in C#
Although C# has assimilated many functional features along the years, its framework is still mostly imperative and object-oriented; things like switch statements and switch expressions haven’t adopted a safer and more consistent behavior, giving leeway to unwarranted flexibility.
That said, it’s pretty simple to add this behavior to your project through the EditorConfig. Just be careful, as these settings change only the development environment!
[*.cs]
# CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive).
dotnet_diagnostic.CS8509.severity = error
# CS8524: The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value.
dotnet_diagnostic.CS8524.severity = none
- For CS8509, set the severity to
error
. This ensures that the code won’t compile without the switch handling all possible values. - For CS8524, set the severity to
none
. This is important because any default case will automatically cover any missing values, which would render the first setting useless.
Unfortunately, I’m unaware of a setting that will error out if you do use a default case, but you can solve that by adding a code analyzer, if you want.