Switch statement without default when dealing with enumerations

后端 未结 10 2385
萌比男神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:14

    I realize that this is a thread resurrection...

    I personally feel that the way that switch works is correct, and it operates how I would logically want it to.

    I'm surprised to hear such complaining about the default label.

    If you only have a strict set of enums or values that you are testing, you don't need all of the exception handling lines, or a return outside of the switch, etc.

    Just put the default label over one of the other labels, perhaps the label that would be the most common response. In your example case it probably doesn't matter which one. Short, sweet, and it fulfills your needs to rid of the compiler warning:

    switch (decision)
    {
        default:
        case Decision.Yes:
            return "Yes, that's my decision";
        case Decision.No:
            return "No, that's my decision";
    }
    

    If you don't want the default to be Yes, put the default label above the No label.

提交回复
热议问题