Is there a way to get the C# compiler to emit an error if a switch(enum_val) is missing a case statement?

前端 未结 8 1871
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 04:27

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

相关标签:
8条回答
  • 2020-12-06 05:11

    You can use a meta-method that checks at runtime, but at least checks the whole switch.

    https://github.com/faisalmansoor/MiscUtil/blob/master/EnumSwitch/EnumSwitch.cs

    0 讨论(0)
  • 2020-12-06 05:14

    No there's no compile-time way to make that happen. However the very VERY simple answer is to have a default handler which simply throws an exception along the lines of, "this option wasn't handled, boo".

    switch (c)
    {
        case Colors.Red:  // no error, Red is a Color
            break;
        case Colors.Blue:
        case Colors.Green:  // no error, Blue and Green handled as well
            break;
        default:
            throw new Exception("Unhandled option: " + c.ToString());
    }
    
    0 讨论(0)
提交回复
热议问题