Switch statement without default when dealing with enumerations

后端 未结 10 2362
萌比男神i
萌比男神i 2020-12-15 15:59

This has been a pet peeve of mine since I started using .NET but I was curious in case I was missing something. My code snippet won\'t compile (please forgive the forced nat

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 16:03

    Heck, the situation is far worse than just dealing with enums. We don't even do this for bools!

    public class Test {        
      public string GetDecision(bool decision) {
        switch (decision) {
           case true: return "Yes, that's my decision";                
           case false: return "No, that's my decision"; 
        }
      }
    }
    

    Produces the same error.

    Even if you solved all the problems with enums being able to take on any value, you'd still have this issue. The flow analysis rules of the language simply do not consider switches without defaults to be "exhaustive" of all possible code paths, even when you and I know they are.

    I would like very much to fix that, but frankly, we have many higher priorities than fixing this silly little issue, so we've never gotten around to it.

提交回复
热议问题