Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Ensure Valid Enum Values - Futureproof Method
    primarykey
    data
    text
    <p>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.<br> 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?</p> <p>e.g. (the example below's purely theoretical; I chose statuses from the development lifecycle to ensure it's something familiar to most).</p> <pre><code>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 { } </code></pre> <p>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?</p> <p>Thanks in advance,</p> <p>JB</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload