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

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.

© 2019 - 2024 · dasein · Powered by Hugo ·