I'm writing some code with a simple switch statement based on Enum values. It occurred to me that at some point in future a developer may add a new value, so I included a default method to capture this at runtime and throw an exception. However I realised that I should do this every time I put in logic like this, and that I'd only see such issues at run time rather than compile time.
I'm wonderring if there's some code I can add to get the compiler to tell the developer that they need to update certain methods in the case that they update enum values - beyond just adding comments to the enum itself?
e.g. (the example below's purely theoretical; I chose statuses from the development lifecycle to ensure it's something familiar to most).
public enum DevelopmentStatusEnum
{
Development
//, QA //this may be added at some point in the future (or any other status could be)
, SIT
, UAT
, Production
}
public class Example
{
public void ExampleMethod(DevelopmentStatusEnum status)
{
switch (status)
{
case DevelopmentStatusEnum.Development: DoSomething(); break;
case DevelopmentStatusEnum.SIT: DoSomething(); break;
case DevelopmentStatusEnum.UAT: DoSomething(); break;
case DevelopmentStatusEnum.Production: DoSomething(); break;
default: throw new StupidProgrammerException(); //I'd like the compiler to ensure that this line never runs, even if a programmer edits the values available to the enum, alerting the program to add a new case statement for the new enum value
}
}
public void DoSomething() { }
}
public class StupidProgrammerException: InvalidOperationException { }
This is a bit academic, but I can see it as being useful in making my app robust. Has anyone tried this before / got any good ideas on how this might be achieved?
Thanks in advance,
JB