Consider the following code :
private enum myEnum
{
A,
B
}
private void myMethod(myEnum m)
{
switch (m)
{
case myEnum.A:
//do stuff
break;
case myEnum.B:
//do stuff
break;
default:
throw new NotImplementedException(m.ToString());
}
}
If I ever add a third member C to myEnum, I will only be warned at runtime by a NotImplementedException
What I'd like to do is have the compiler warn me when there's a switch with unhandled cases and no default: case.
Is there a way to do that, or other solution to this problem, the ultimate goal being to be warned at compile-time that something is missing?
Unfortunately here is no compiler feature to do this for you.
Instead of having an enum, have a base class or an interface. MyMethod is defined on the interface.
Each each enum member now becomes a class with different behaviour for myMethod. If you add a class (to extend the options, currently you'd add an enum item)but don't implement myMethod, you'll get a compiler error.
having lots of place's in code where you provide different behaviour in select statements is a smell that you may need to use polymorphism.
EDIT
The best advice I can give is to build unit tests for each function that relies on the switch statement, and call it for each value in the enumeration (you can get the values at runtime with the GetValues member on the Enum class)
No, there's nothing in the language to check this.
You can have a:
default:
throw new ArgumentOutOfRangeException("Invalid value or bug");
case, but obviously that's execution-time rather than compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With