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

前端 未结 8 1887
佛祖请我去吃肉
佛祖请我去吃肉 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 04:50

    The C# compiler doesn't have this check built-in, but there's a code contracts checker for .Net that does: https://blogs.msdn.microsoft.com/francesco/2014/09/12/how-to-use-cccheck-to-prove-no-case-is-forgotten/

    The technique is to use a code contract assertion to tell the checker that the default case should never be reachable:

    switch (c) {
      case Colors.Red: break;
      case Colors.Blue:
      case Colors.Green: break;
      default:
        Contract.Assert(false); // Tell static checker this shouldn't happen
    }
    

    Then, if the checker sees that it is reachable (because one of the enum values is not handled), it will warn you:

    warning : CodeContracts: This assert, always leading to an error, may be reachable.
    Are you missing an enum case?
    

提交回复
热议问题