I just realized I added a value to the list of \"must-handle\" values in my enum, but I didn\'t catch it until runtime. I know the C# compiler is really powerful when it com
You could throw an exception early on if the enum size, hopefully alerting you very early on when a change to the enum has been made:
enum MyEnum {A, B};
class TestEnum
{
// Static constructor
static TestEnum()
{
// Check if this code needs updating as the enum has changed
if (Enum.GetNames(typeof(MyEnum)).Length != 2)
{
// If this fails update myFunction and the number above
throw new Exception("Internal error - code inconsistency");
}
}
// My function that switches on the enum
string myFunction(MyEnum myEnum)
{
switch (myEnum)
{
case MyEnum.A: return "A";
case MyEnum.B: return "B";
}
throw new Exception("Internal error - missing case");
}
}
This will throw an exception from the static constructor if the number of items in the enum is changed. So the developer knows he needs to update the code. You could even do this check from a unit test that you run with your build.