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

前端 未结 8 1900
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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());
    }
    

提交回复
热议问题