Switch statement without default when dealing with enumerations

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

    That's because the value of decision could actually be a value that is not part of the enumeration, for instance :

    string s = GetDecision((Decision)42);
    

    This kind of thing is not prevented by the compiler or the CLR. The value could also be a combination of enum values :

    string s = GetDecision(Decision.Yes | Decision.No);
    

    (even if the enum doesn't have the Flags attribute)

    Because of that, you should always put a default case in you switch, since you can't check all possible values explicitly

提交回复
热议问题