Should an Enum start with a 0 or a 1?

前端 未结 14 1374
别那么骄傲
别那么骄傲 2020-12-04 10:19

Imagine I have defined the following Enum:

public enum Status : byte
{
    Inactive = 1,
    Active = 2,
}

What\'s the best practice to use

相关标签:
14条回答
  • 2020-12-04 11:18

    Don't start them at 0 unless there's a reason to, such as using them as indices to an array or list, or if there's some other practical reason (like using them in bitwise operations).

    Your enum should start exactly where it needs to. It needn't be sequential, either. The values, if they are explicitly set, need to reflect some semantic meaning or practical consideration. For example, an enum of "bottles on the wall" should be numbered from 1 to 99, while an enum for powers of 4 should probably start at 4 and continue with 16, 64, 256, etc.

    Furthermore, adding a zero-valued element to the enum should only be done if it represents a valid state. Sometimes "none," "unknown," "missing," etc. are valid values, but many times they are not.

    0 讨论(0)
  • 2020-12-04 11:19

    Don't assign any numbers. Just use it like it supposed to be used.

    0 讨论(0)
提交回复
热议问题