Should an Enum start with a 0 or a 1?

前端 未结 14 1419
别那么骄傲
别那么骄傲 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:07

    I would say, it depends on how you use them. For flagging enum it is a good practice to have 0 for None value, like that:

    [Flags]
    enum MyEnum
    {
        None = 0,
        Option1 = 1,
        Option2 = 2,
        Option3 = 4,
        All = Option1 | Option2 | Option3,
    }
    

    When your enum is likely to be mapped to a database lookup table, I'd start it with 1. It should not matter much for professionally written code, but this improves readability.

    In other cases I'd leave it as it is, giving no care whether they start with 0 or 1.

提交回复
热议问题